PowerShell: How to Create Folder if it Does Not Exist


You can use the following syntax in PowerShell to create a folder only if it does not already exist:

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

This particular example tries to create a folder named west_data in a particular location.

If the folder already exists, then we receive the following message:

  • “This folder already exists”

If the folder does not already exist then it will be created and we will receive the following message:

  • “New folder successfully created”

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

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

Example: How to Create Folder if it Does Not Exist in PowerShell

Suppose that our current directory has the following path:

  • c:/users/bobbi/data1

We can use the following syntax to list out all folders that exist in this directory:

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

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

We can see that four folders exist in this directory:

  • central_data
  • east_data
  • pacific_data
  • south_data
  • west_data

Suppose that we would attempt to create a new folder in this directory named west_data:

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

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

PowerShell create folder if not exists

The output displays “This folder already exists” because there is indeed a folder named west_data that already exists in this directory.

Suppose instead we try to create a folder named north_data:

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

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

We can see that a new folder named north_data has been created and we receive the message “New folder successfully created” to let us know that it was created.

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