Limiting Variables to a set of values

by Feb 3, 2009

By adding a ValidateSetAttribute to a variable, you can force it to accept only values that match a given set.

Once you add this attribute in the next example, the variable $option can only accept the values yes, no or perhaps:

$option = "yes"
(Get-variable option).Attributes.Add(
$(New-Object System.Management.Automation.ValidateSetAttribute `
-ArgumentList "yes", "no", "perhaps"))
$option = "no"
$option = "perhaps"
# illegal assignment, causes exception:
$option = "don't know"
$option = "perhaps"