Using a PowerShell Parameter Validator

by Mar 24, 2017

PowerShell function parameters support a ValidateScript attribute where you can assign PowerShell code. The code is invoked when the parameter receives a value from a user, and can return $true or $false. If the code returns $false, the argument is rejected.

Here is a sample that accepts file names only if the file exists in the Windows folder:

function Get-File
{
    param
    (
        [Parameter(Mandatory)]
        [ValidateScript({ Test-Path -Path "$env:windir\$_" })]
        [string]
        $File
    )

    "$File exists in your Windows folder."
}

And here is a result:

 
PS C:\> Get-File  -File explorer.exe
explorer.exe exists  in your Windows folder.
 
PS C:\> Get-File  -File something.exe
Get-File : Cannot validate argument on parameter  'File'. The " Test-Path -Path "$env:windir\$_" " validation  script for the argument with value "something.exe" did not return a  result of True. Determine why the validation script failed, and then try the  command again.
At line:1 char:16
+ Get-File -File something.exe
+                 ~~~~~~~~~~~~~
    +  CategoryInfo          : InvalidData: (:)  [Get-File], ParameterBindingValidationException
    +  FullyQualifiedErrorId : ParameterArgumentValidationError,Get-File  
 
PS C:\> Get-File  -File memory.dmp
memory.dmp exists in  your Windows folder.
 

Twitter This Tip! ReTweet this Tip!