🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Parameter Validation

Parameter validation is a set of rules on a parameter that reject bad input before the function body runs. It stops bad values at the door instead of letting them cause trouble inside.

ValidateSet allows only listed values

The color must come from the list, and Green is on it.

function Show-Color {
    param([ValidateSet("Red", "Green", "Blue")][string]$Color)
    "Color: $Color"
}
Show-Color -Color "Green"

ValidateRange allows only numbers in range

The age must sit between 1 and 10, and 7 does.

function Show-Age {
    param([ValidateRange(1, 10)][int]$Age)
    "Age: $Age"
}
Show-Age -Age 7

ValidatePattern allows only matching text

The code must be three capital letters, and ABC matches.

function Show-Code {
    param([ValidatePattern("^[A-Z]{3}$")][string]$Code)
    "Code: $Code"
}
Show-Code -Code "ABC"

A bad value gives a real error message

Yellow is not on the list, so the call fails and try and catch print the real message.

function Show-Color {
    param([ValidateSet("Red", "Green", "Blue")][string]$Color)
    "Color: $Color"
}
try {
    Show-Color -Color "Yellow" -ErrorAction Stop
} catch {
    "Caught: " + $_.Exception.Message
}

Example

function New-Greeting {
    param(
        [Parameter(Mandatory = $true)][string]$Name,
        [ValidateSet("Hello", "Hi")][string]$Word = "Hello",
        [ValidateRange(1, 3)][int]$Times = 1
    )
    for ($i = 0; $i -lt $Times; $i++) {
        "$Word $Name"
    }
}
New-Greeting -Name "Ana" -Word "Hi" -Times 2

Key points

  • ValidateSet: a rule that accepts only values from a fixed list.
  • ValidateRange: a rule that accepts only numbers between a lowest and a highest value.
  • ValidatePattern: a rule that accepts only text matching a pattern.
  • Mandatory: a rule that requires a value, so the call must supply it.
  • Use validation rules to catch mistakes early, with a clear error message.

In this example, a greeting function requires a name, allows only Hello or Hi for the word, and allows the count only from 1 to 3. The call supplies all three values, so the greeting prints twice.

Note

A validation error names the parameter and the rule, which makes the mistake easy to find.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which rule accepts only numbers from 1 to 10?