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.
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.
But watch what happens when I try to use a value outside of the accepted range:
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.
If I later decide to change the value, the validation will help me catch typos.
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.
Recommend0 recommendationsPublished in