In the previous tip we illustrated how the new "enum" keyword works in PowerShell 5.0 to set the values that are assignable to a parameter. This has two backdraws: it works in PowerShell 5.0 only, and the enum needs to be declared before you can run the function.

If all you want is limiting choices, you can use a ValidateSet attribute instead. It is supported in older PowerShell versions and part of the function code:

#requires -Version 2
function Select-City
{
  param
  (
    [ValidateSet('Hannover','Seattle','London','NewYork')]
    [Parameter(Mandatory=$true)]
    $City
  )
  
  "You chose $City"
}

ValidateSets provide smart IntelliSense in PowerShell ISE, just like enumerations do.

Twitter This Tip! ReTweet this Tip!

Anonymous