Controlling Numeric Range for Variables

by Aug 1, 2013

In a previous tip we illustrated how in PowerShell 3.0, you can now use validators to restrict the data that can be assigned to a variable.

Here is another example. It assigns the data type "Int32" to a variable, so it only accepts numeric values. In addition, it adds a ValidateRange attribute, forcing the variable to numeric values in the range from 1 to 10:

[Int32][ValidateRange(1,10)]$id = 1 

And this is how the variable responds to different assignments:

Twitter This Tip! ReTweet this Tip!