PowerShell PowerShell Functions Parameter Validation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

There are a variety of ways to validate parameter entry, in PowerShell.

Instead of writing code within functions or scripts to validate parameter values, these ParameterAttributes will throw if invalid values are passed.

ValidateSet

Sometimes we need to restrict the possible values that a parameter can accept. Say we want to allow only red, green and blue for the $Color parameter in a script or function.

We can use the ValidateSet parameter attribute to restrict this. It has the additional benefit of allowing tab completion when setting this argument (in some environments).

param(
    [ValidateSet('red','green','blue',IgnoreCase)]
    [string]$Color
)

You can also specify IgnoreCase to disable case sensitivity.

ValidateRange

This method of parameter validation takes a min and max Int32 value, and requires the parameter to be within that range.

param(
    [ValidateRange(0,120)]
    [Int]$Age
)

ValidatePattern

This method of parameter validation accepts parameters that match the regex pattern specified.

param(
    [ValidatePattern("\w{4-6}\d{2}")]
    [string]$UserName
)

ValidateLength

This method of parameter validation tests the length of the passed string.

param(
    [ValidateLength(0,15)]
    [String]$PhoneNumber
)

ValidateCount

This method of parameter validation tests the amount of arguments passed in, for example, an array of strings.

param(
    [ValidateCount(1,5)]
    [String[]]$ComputerName
)

ValidateScript

Finally, the ValidateScript method is extraordinarily flexible, taking a scriptblock and evaluating it using $_ to represent the passed argument. It then passes the argument if the result is $true (including any output as valid).

This can be used to test that a file exists:

param(
    [ValidateScript({Test-Path $_})]
    [IO.FileInfo]$Path 
)

To check that a user exists in AD:

param(
    [ValidateScript({Get-ADUser $_})]
    [String]$UserName
)

And pretty much anything else you can write (as it's not restricted to oneliners):

param(
    [ValidateScript({
        $AnHourAgo = (Get-Date).AddHours(-1)
        if ($_ -lt $AnHourAgo.AddMinutes(5) -and $_ -gt $AnHourAgo.AddMinutes(-5)) {
            $true
        } else {
            throw "That's not within five minutes. Try again."
        }
    })]
    [String]$TimeAboutAnHourAgo
)


Got any PowerShell Question?