Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a path is a folder or a file in PowerShell

Tags:

powershell

I'm trying to write a PowerShell script which goes through a list of values which are folder or file paths, and delete the files first, then remove the empty folders.

My script so far:

[xml]$XmlDocument = Get-Content -Path h:\List_Files.resp.xml $Files =  XmlDocument.OUTPUT.databrowse_BrowseResponse.browseResult.dataResultSet.Path 

Now I'm trying to test each line in the variable to see if it's a file and delete it first, and then go through and remove subfolders and folders. This is just so that it's a clean process.

I can't quite get this next bit to work, but I think I need something like:

foreach ($file in $Files) {     if (! $_.PSIsContainer)     {         Remove-Item $_.FullName}     } } 

The next section can clean up the subfolders and folders.

Any suggestions?

like image 236
Stefan Hattrell Avatar asked Oct 03 '16 06:10

Stefan Hattrell


People also ask

How do I search for a file in a directory in PowerShell?

To search the content in the file in PowerShell, you need to first get the content from the file using Get-Content command and then you need to add Select-String pipeline command. In the below example, we need to search the lines which contain the Get word. You can use multiple patterns to search for the result.

How do I find my PowerShell path?

List $Env:Path with PowerShell. You can also see path values in the Control Panel; navigate to the System section and then click on the link to 'Advanced system settings'.

What is PathType leaf in PowerShell?

-Leaf. An element that does not contain other elements, such as a file. The easiest way to get this information from the console is Get-Help Test-Path -Parameter PathType.

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.


1 Answers

I found a workaround for this question: use Test-Path cmdlet with the parameter -FileType equal to Leaf for checking if it is a file or Container for checking if it is a folder:

# Check if file (works with files with and without extension) Test-Path -Path 'C:\Demo\FileWithExtension.txt' -PathType Leaf Test-Path -Path 'C:\Demo\FileWithoutExtension' -PathType Leaf  # Check if folder Test-Path -Path 'C:\Demo' -PathType Container 

Demo

I originally found the solution here. And the official reference is here.

like image 178
Alicia Avatar answered Sep 30 '22 21:09

Alicia