Adding ValidateRange to a Variable

by Oct 9, 2015

If you'd like to apply a numeric range of legal values to a variable, you can add a ValidateRange attribute to the variable, pretty much like function parameters work. Except, with variables you need to do it manually:

$test = 1
$variable = Get-Variable test
$validateRange = New-Object -TypeName System.Management.Automation.ValidateRangeAttribute(1,100)
$variable.Attributes.Add($validateRange)

$test = 10
$test = 100
$test = 1000 

The variable $test now accepts numeric values in the range from 1 to 100. When you try and assign a value outside the range, you get an exception.

 
PS C:\> $test =  101
The variable cannot be  validated because the value 101 is not a valid value for the test 
variable.
At line:1 char:1
+ $test = 101
+ ~~~~~~~~~~~
    +  CategoryInfo          : MetadataError:  (:) [], ValidationMetadataException
    +  FullyQualifiedErrorId : ValidateSetFailure 
 

Twitter This Tip! ReTweet this Tip!