Validating Variable Content

by Aug 24, 2018

Beginning in PowerShell 5, you can assign a validator to a variable. The validator can take a regular expression, and once you assign new values to the variable, the validator checks to see whether the new content matches the regular expression pattern. If not, an exception is thrown, and the variable content stays untouched.

Here is an example showing a variable that stores MAC addresses:

[ValidatePattern('^[a-fA-F0-9:]{17}|[a-fA-F0-9]{12}$')][string]$mac = '12:AB:02:33:12:22'

Run the code, then try and assign a new mac address to the variable. If it does not match the validator, PowerShell throws an exception.

Twitter This Tip! ReTweet this Tip!