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!

Anonymous
  • Unfortunately, the following would pass the above validation: "1:2:3:4:5:6:7:8:9"

    Instead, use the following regular expression to ensure it follows the exact MAC address format:

    ^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$

    This would be the entire line:

    [ValidatePattern('^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$')][string]$mac = '12:34:56:78:90:AB'