Validate $Path Parameter Exists & Is Folder - Issue with Spaces

Viewed 249

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.

1 Answers

What can explain your script validation failing is that you're not quoting the path with spaces, an easy way of testing this using Write-Host $_ on your ValidateScript attribute:

  • Given script.ps1:
param (
  [Parameter(Mandatory)]
  [ValidateScript({ Write-Host $_; $true })]
  [String]$Path
)

Testing the parameter without quotes:

PS /> ./script.ps1 /path/with spaces

/path/with # => This is Write-Host $_
script2.ps1: A positional parameter cannot be found that accepts argument 'spaces'.

As you can see, in PowerShell, if you want to bound an argument with a parameter, and said argument (string) has spaces, the value must be enclosed in quotation marks, or the spaces must be preceded by the escape character (`).

PS /> ./script.ps1 '/path/with spaces' 
/path/with spaces

PS /> ./script.ps1 /path/with` spaces
/path/with spaces

As for, how you can improve the path validation, what you're doing seems fine. You could swap the order of the condition so it's more straight forward:

param(
  [ValidateScript({ 
      if(Test-Path $_ -PathType Container) {
          return $true
      }
      elseif(Test-Path $_ -PathType Leaf) {
          throw 'The Path parameter must be a folder. File paths are not allowed.'
      }
      throw 'Invalid File Path'
  })]
  [string]$Path
)
Related