How to validate the path with the PowerShell function parameter?


To validate the file or folder path inside the PowerShell function parameter, we need to use the ValidateScript command. Generally, we write the script as below to validate the path.

function Validate-Path{
   param(
      [parameter(Mandatory)]
      [String]$Path
   )
   if(Test-Path $Path) {Write-Output "Path is valid"}
   else{Write-Output "Path is invalid"}
}

Output

PS C:\> Validate-Path -Path C:\Temp
Path is valid

We can add similar functionality inside the function parameter with the validatescript argument so the script will throw the error initially at the parameters check. See below,

function Validate-Path{
   param(
      [parameter(Mandatory)]
      [ValidateScript({
      if(Test-Path $_){$true}
         else{throw "Path $_ is not valid"}
      })]
      [String]$Path
   )
   Write-Output "Executing Script further"
}

Output

Valid Path

PS C:\> Validate-Path -Path C:\Temp
Executing Script further

InValid Path

PS C:\> Validate-Path -Path C:\Temp223
Validate-Path : Cannot validate argument on parameter 'Path'. Path C:\Temp223 is not valid
At line:1 char:21
+ Validate-Path -Path C:\Temp223
+ ~~~~~~~~~~
   + CategoryInfo : InvalidData: (:) [Validate-Path], ParameterBindingValidationException
   + FullyQualifiedErrorId : ParameterArgumentValidationError,Validate-Path

In the above example, if the path is valid, the script will continue execution but if the path is not valid then it will throw an exception and the script is terminated.

Updated on: 17-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements