Define Variable Checkers

by Jul 26, 2013

When you assign a mandatory data type to a variable, then this will improve script robustness: whenever a value is (accidentally) assigned to that variable that does not match the expected type, an error is raised.

In PowerShell 3.0, this concept can be further refined. All validation attributes that previously only worked for parameters now also work for variables.

Here is an example:

[String][ValidateSet('dom1', 'dom2', 'dom3')]$domain = 'dom1'

The variable $domain now accepts only strings, and because of the ValidateSet attribute, the list of allowable domain names are "dom1", "dom2" and "dom3". Try and assign a different string to $domain, and you get an error message indicating the problem.

To get a list of validation attributes you can use, execute the following command:

This line requires PowerShell 3.0 and assumes that you downloaded the PowerShell help first using Update-Help. In PowerShell 2.0, omit the parameter -ShowWindow.

Twitter This Tip! ReTweet this Tip!