Adding a Conditional to Check if a Path Exists and Create it if Not
In PowerShell, you can use the Test-Path cmdlet to check if a path exists, and then conditionally create it if it doesn't. Here are several approaches to accomplish this task with varying levels of complexity and error handling.
Basic Approach
The simplest way to check if a directory exists and create it if it doesn't:
$folderPath = "C:\Example\Path"
if (-not (Test-Path -Path $folderPath)) {
New-Item -Path $folderPath -ItemType Directory
Write-Host "Directory created: $folderPath"
} else {
Write-Host "Directory already exists: $folderPath"
}
This code uses Test-Path to check if the folder exists, and if not, it creates the directory using the New-Item cmdlet[1][5].
Robust Error Handling Approach
For a more robust solution with error handling:
$folderPath = "C:\Example\Path"
if (-not (Test-Path -LiteralPath $folderPath)) {
try {
New-Item -Path $folderPath -ItemType Directory -ErrorAction Stop | Out-Null
Write-Host "Successfully created directory '$folderPath'."
} catch {
Write-Host "Unable to create directory '$folderPath'. Error was: $_" -ErrorAction Stop
}
} else {
Write-Host "Directory already exists."
}
This approach adds:
- The
-LiteralPath parameter which treats the path literally without interpreting wildcards[6]
- A
try/catch block to handle potential errors (like permission issues)
- The
-ErrorAction Stop parameter to ensure errors trigger the catch block
Out-Null to suppress the default output of the New-Item cmdlet[6]
Creating Nested Directories
To create nested directories (creating parent directories if they don't exist):
$folderPath = "C:\Parent\Child\Grandchild"
if (-not (Test-Path -Path $folderPath)) {
New-Item -Path $folderPath -ItemType Directory -Force
Write-Host "Directory structure created: $folderPath"
} else {
Write-Host "Directory structure already exists: $folderPath"
}
The -Force parameter ensures that all parent directories in the path are created if they don't exist[6].
Using Other Approaches
Using .NET Method
You can also use the .NET Framework's System.IO.Directory class:
$folderPath = "C:\Example\Path"
if (-not ([System.IO.Directory]::Exists($folderPath))) {
[System.IO.Directory]::CreateDirectory($folderPath)
Write-Host "Directory created: $folderPath"
} else {
Write-Host "Directory already exists: $folderPath"
}