Parameter Validation

suggest change

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 attributes 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=$false)]
    [string]$Color
)

IgnoreCase defaults to $true, so red and RED are both accepted. Set IgnoreCase=$false to require the case in the set.

ValidateRange

This attribute takes a minimum and a maximum value, and requires the parameter to be within that range.

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

ValidatePattern

This attribute accepts values that match the regex pattern. ValidatePattern is not anchored, so the pattern below uses ^ and $ to match the whole value. \w includes digits.

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 attribute tests the number of arguments passed in, for example an array of strings.

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

ValidateScript

ValidateScript takes a script block and evaluates it using $_ as the passed argument. Validation succeeds when the script block's output is true. $false, $null, 0, and no output fail validation.

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 (it is not restricted to one-liners):

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."
        }
    })]
    [datetime]$TimeAboutAnHourAgo
)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents