Using ValidatePattern attribute

by Jul 19, 2013

PowerShell can validate parameters using regular expressions. This example accepts only computer names that start with "PC" followed by three digits:

function Get-PCInfo {
   param 
   (
     [ValidatePattern(
      '^PC\d{3}$'
     )]
     [String]
     $ComputerName
   )
 
    "Examining $ComputerName"
} 

Unfortunately, when a user enters a computer name that does not match the pattern, the error message is very cryptic and basically only states that the entered value does not match the regular expression.

A better way as pointed out by Bartek Bielawski on powershellmagazine.com (http://www.powershellmagazine.com/2013/05/08/pstip-validatepattern-friendlier-error-messages/) may be by adding a comment to your regular expression like this:

function Get-PCInfo {
   param 
   (
     [ValidatePattern(
      '(?# Enter a PC Name starting with PC followed by 3 digits)^PC\d{3}$'
     )]
     [String]
     $ComputerName
   )
 
    "Examining $ComputerName"
} 

Now, the error message is still pretty ugly but at least, the comment gives an easy clue what might be wrong with the supplied value.

If you want full control over the error message, then you must post-process the parameter value like this:

function Get-PCInfo {
   param (
     [String]
     $ComputerName
   )
   
   if ($ComputerName -notmatch '^PC\d{3}$')
   {
     Throw 'Get-PCInfo : ComputerName is invalid. Use this format: PCxxx'
   }

   "Examining $ComputerName"
} 

Here is the result:

Twitter This Tip! ReTweet this Tip!