Using Custom Validation Attributes

by Apr 24, 2020

Beginning in PowerShell 5, you can create your own attributes, i.e. custom validators. They can be applied to variables (and parameters), and once a value is assigned that does not match the validator, an exception is raised.

Here is an example for a path validator. When you apply it to a variable, only valid file paths can be applied to the variable:

class ValidatePathExistsAttribute : System.Management.Automation.ValidateArgumentsAttribute
{
    # the value to be checked surfaces in $path and must be of type [object]
    [void]Validate([object]$path, [System.Management.Automation.EngineIntrinsics]$engineIntrinsics)
    {
        # if anything is wrong with the value, throw an exception
        if([string]::IsNullOrWhiteSpace($path))
        {
            Throw [System.ArgumentNullException]::new()
        }
        if(-not (Test-Path -Path $path))
        {
            Throw [System.IO.FileNotFoundException]::new()
        }        

        # if NO exception was thrown, the value is accepted
    }
}
#endregion


[ValidatePathExists()][string]$Path = "c:\windows"
$Path = "c:\test123"

Whenever you assign a path that does not exist, PowerShell will *not* assign it and instead keep the existing value.


Twitter This Tip! ReTweet this Tip!