'Validate $Path Parameter Exists & Is Folder - Issue with Spaces
I am trying to validate a PowerShell script path parameter. I want to check that it exists and that it is a folder. Here's my parameter setup/validation script:
Param (
[Parameter(Mandatory=$true)]
[ValidateScript({
if( -Not ($_ | Test-Path) ){ throw 'Folder does not exist.' }
if( -Not ($_ | Test-Path -PathType Container) ){ throw 'The Path parameter must be a folder. File paths are not allowed.' }
return $true
})]
[String]$Path
)
Usage: .\script.ps1 -Path "C:\Test Path With Space"
When running this on a path that contains a space, it fails validation with: Folder does not exist.
- What am I doing wrong?
- Is there a better way to approach getting a valid folder path?
Note: I chose to use a String parameter instead of System.IO.FileInfo so that I could ensure there was a trailing \ in the path.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
