PowerShell: How to Check if Folder Exists


You can use the following syntax in PowerShell to check if a folder exists at a specific path:

Test-Path "c:\users\bobbi\data1\current_data"

This particular example checks if a folder exists at the path that we specified.

The Test-Path cmdlet will return True if the folder exists or False otherwise.

You can also use the following syntax to create a folder only if it doesn’t already exist:

$my_folder = "c:\users\bobbi\data1\current_data"
 
if (-not (Test-Path $my_folder)) {
    New-Item -Path $my_folder -ItemType Directory
    Write-Host "A new folder was created"
}
else {
    Write-Host "This folder already exists"
}

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

Example: How to Check if Folder Exists Using PowerShell

Suppose that we would like to check if a folder named current_data exists at the following path:

  • c:\users\bobbi\data1\current_data

We can use the following syntax to do so:

Test-Path "c:\users\bobbi\data1\current_data"

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

PowerShell check if folder exists

This returns True, which indicates that this folder does exist at this specific path.

If we’d like, we can use the following syntax to list out all folders that exist in the data1 parent directory:

Get-ChildItem c:\users\bobbi\data1 -Directory

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

We can see that two folders exist in the data1 directory:

  • current_data
  • new_data

Suppose that we would like to create a new folder named old_data but only if it doesn’t already exist.

We can use the following syntax to do so:

$my_folder = "c:\users\bobbi\data1\old_data"
 
if (-not (Test-Path $my_folder)) {
    New-Item -Path $my_folder -ItemType Directory
    Write-Host "A new folder was created"
}
else {
    Write-Host "This folder already exists"
}

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

PowerShell create folder if it does not exist

The output displays “A new folder was created” which tells us that a folder named old_data did not previously exist but it was successfully created.

We can use the following syntax once again to list out all folders that exist in the data1 parent directory:

Get-ChildItem c:\users\bobbi\data1 -Directory

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

We can see that the new folder named old_data has been added to this directory.

Note: You can find the complete documentation for the Test-Path cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Delete File if it Exists
PowerShell: How to Find Empty Folders
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply