Clever Parameter Validation

by Apr 2, 2015

PowerShell 2.0 and later

When you create PowerShell functions with parameters, make sure you tell PowerShell what kind of values the parameter expects.

In a simple example, you could ask for a weekday:

function Get-Weekday
{
  param
  (
    $Weekday
  )
  
  "You chose $Weekday"
}

The user could submit anything, though, not just weekday names:

 
PS> Get-Weekday -Weekday NoWeekday
You chose NoWeekday                                                 
 

Sometimes, you may see validators using regular expressions:

function Get-Weekday
{
  param
  (
    [ValidatePattern('Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday')]
    $Weekday
  )
  
  "You chose $Weekday"
}

Now, the user is bound to the patterns, and if the value is not part of the regular expression pattern, PowerShell will throw an exception. However, the error message is not very meaningful, and the user won’t get IntelliSense to start with.

A much better approach is to use a validate set:

function Get-Weekday
{
  param
  (
    [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
    $Weekday
  )
  
  "You chose $Weekday"
}

Now, the user can only enter the values you allowed, plus the user will get IntelliSense in the PowerShell ISE, displaying the allowed values.

If you know a .NET enumeration that describes the values you are after, an even easier way is to assign this type to your argument:

function Get-Weekday
{
  param
  (
    [System.DayOfWeek]
    $Weekday
  )
  
  "You chose $Weekday"
}

Twitter This Tip! ReTweet this Tip!