Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Variable Validation

Posted on October 26, 2012

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.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

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.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

3 thoughts on “Variable Validation”

  1. Trevor Sullivan (@pcgeek86) says:
    October 28, 2012 at 12:26 pm

    Great post, Jeff. I’ve also done some of my own testing, and validated (no pun intended) that you can use the $_ automatic variable with the [ValidateScript()] attribute.

    Here is an example of the above:

    [ValidateScript({@(1,2,3) -contains $_})]$b = 4;
    Attribute cannot be added because it would cause the variable b with value 4 to become invalid.
    At line:1 char:1

    Something else that should be pointed out is that a variable must be initialized before the attribute can be added:

    Remove-Variable -Name b -ErrorAction SilentlyContinue;
    [ValidateScript({@(1,2,3) -contains $_})]$b;
    $b = 4; # This works fine

    1. Jeffery Hicks says:
      October 28, 2012 at 12:38 pm

      Thanks for adding to the conversation.

  2. Peter Kriegel says:
    October 29, 2012 at 12:59 pm

    Hi Jeffery!

    Thank you for enlighten me! This is very needfull in combination with strict mode!
    I have reposted, retweeted reshared this ;-))

    http://www.admin-source.de

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d