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