Creating Enumerations

by Nov 3, 2015

PowerShell 5.0 added the capabilities to define enumerations but in older PowerShell versions, you can create enumerations too, simply by compiling the appropriate C# code:

#requires -Version 2


$code = @"
public enum Cities
{
    NewYork,
    Hamburg,
    HongKong
}

"@


$type = Add-type -TypeDefinition $code -PassThru

function Get-City
{
    param
    (
        [Cities]
        $City
    )
    
    "You chose $City"
}

When you add the enumeration type to a parameter, PowerShell automatically adds completion, and the ISE editor shows an IntelliSense menu.

If you like to achieve the same without specific types, you can use the string type and add a ValidateSet attribute like this:

#requires -Version 2

function Get-City
{
    param
    (
        [ValidateSet('NewYork','Hamburg','Hongkong')]
        [String]
        $City
    )
    
    "You chose $City"
}

The latter approach will not show the allowed values in the function syntax, though.

Twitter This Tip! ReTweet this Tip!