Validation Attributes On Variables

by Oct 30, 2012

In PowerShell v2, function parameters could be decorated with validation attributes. In PowerShell v3, these attributes can now also be applied to plain variables, ensuring for example that they keep a certain range, thus producing more robust code:

PS> [ValidateRange(1,10)][int]$x = 5
PS> $x=12
The variable cannot be validated because the value 12 is not a valid value for the x
At line:1 char:1
+ $x=12
+ ~~~~~
    + CategoryInfo          : MetadataError: (:) [], ValidationMetadataException
    + FullyQualifiedErrorId : ValidateSetFailure

Twitter This Tip! ReTweet this Tip!