Variable Validation

In PowerShell v3 there is a new feature you might not be aware of that could save you pain and headaches. This is something you could use in scripting as well as the console. In fact, I think using it in the console is an especially smart idea.

In PowerShell v2 scripts and functions we had the ability to add validation tags to parameters. These tags could perform different validation tests on a parameter value. If the value failed, the script or function would throw an exception. I’d rather have the command fail to start than to fail halfway through. Now in PowerShell v3 we can use these same tags on variables in our scripts and even the console. I’ve written about a number of these validation tags in the past on my blog. Here’s an example of what we can do in v3.

PS C:\> [validateRange(1,10)]$i=5

In this example I’ve added a validation test to verify that any value for $i is between 1 and 10. I can use the variable as I normally would. Even change the value.

PS C:\> $i*2
10
PS C:\> $i+=1
PS C:\> $i*2
12

But watch what happens when I try to use a value outside of the accepted range:

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

I get an exception. This is much better than setting a value that will cause another error later. The sooner you can detect potential problems the better.

Perhaps this example isn’t compelling. But there are other validation tests you might want to take advantage of. Maybe a regular expression pattern.

PS C:\> [validatepattern({\\\\\w+\\\w+})]$unc="\\server01\share"

If I later decide to change the value, the validation will help me catch typos.

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

The bottom line is that if your variable values will change, using a validation tag will ensure new values will work. If you don’t want to sift through the blog learning more about the validation tags, take a look at my Scripting Help module.

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to FriendFeed Post to Google Buzz Post to Ping.fm Post to Reddit Post to Slashdot Post to StumbleUpon Post to Technorati

About the Author

PowerShell.org Announcer

This is the official account for PowerShell.org and sponsor announcements.