PowerShell: How to Check if a Path is a Folder or a File


Often you may want to check if a path is a folder or a file in PowerShell.

You can use the following basic syntax to do so:

$my_path = Get-Item "C:\some\path"

if($my_path.PSIsContainer) {
    Write-Host "Path is a folder"
} else {
    Write-Host "Path is a file"
}

This particular example will check if the path specified in the $my_path variable is a folder or a file and output the appropriate result to the console.

This particular syntax checks if the PSIsContainer property of the path is True or False.

All folders are considered “containers” and thus have a PSIsContainer property of True.

Conversely, all files are not considered “containers” and thus have a PSIsContainer property of False.

By using an if else statement we can simply check if the value of the PSIsContainer property is True or False and output the corresponding result.

The following example shows how to use this syntax in practice.

Example: How to Check if Path is a Folder or File in PowerShell

Suppose that we would like to check if the following path is a folder or a file:

  • C:\Users\bobbi\data2

We can use the following syntax to do so:

$my_path = Get-Item "C:\Users\bobbi\data2"

if($my_path.PSIsContainer) {
    Write-Host "Path is a folder"
} else {
    Write-Host "Path is a file"
}

The following screenshot shows how to use this syntax in practice:

This returns “Path is a folder” since the path that we specified does indeed represent the path to a folder named data2.

Suppose instead that we would like to check if the following path is a folder or a file:

  • C:\Users\bobbi\data2\all_teams.csv

We can use the following syntax to do so:

$my_path = Get-Item "C:\Users\bobbi\data2\all_teams.csv"

if($my_path.PSIsContainer) {
    Write-Host "Path is a folder"
} else {
    Write-Host "Path is a file"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if path is a file

This returns “Path is a file” since the path that we specified does indeed represent the path to a file named all_teams.csv.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get Relative Path of File
PowerShell: How to Get File Name from Path
PowerShell: How to Get Last Folder in Path

Leave a Reply