How-to: Create and use PowerShell enums

An Enum type is a data type (enumerated type) that restricts the value of a variable to be a set of predefined constants.

When a variable is set to an Enum value, it will have both an integer value plus a more descriptive string.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
You can also define specific integer values for each enum value (Spring = 10, Summer = 50, ...)

Create an Enum

Define a new enum using Add-Type. Once the enum type has been added to the console environment, it can not be removed or re-defined. Closing and re-opening the console session will remove the enum.

Create an enum called MySeasons for the 4 seasons:

Add-Type -TypeDefinition @"
   public enum MySeasons {
      Spring,
      Summer,
      Autumn,
      Winter
   }
"@

In PowerShell 5.0+, the enum keyword makes this even easier. Note this is NOT comma-separated.

enum MySeasons {
   Spring
   Summer
   Autumn
   Winter = 25
}

The name for the enum cannot contain spaces or any special characters other than an underscore. Also the name cannot be a number and the first character must not be numeric. So "SS64" could be used as a name but not "64SS".

Set the value of an Enum variable

Create a variable of this TYPE and set it to one of the allowed values

[MySeasons]$Season = [MySeasons]::Winter

An alternative option is to cast a string containing a valid enum name into the enum type:

[MySeasons]$Season = [MySeasons] 'Winter'

An explicit cast (or even the whole type name) is rarely required, so this will also work:

$Season = [MySeasons] 'Winter'

If we try this with an undefined/invalid value, it will fail and display the valid enumeration values:

$ThisWillFail = [MySeasons]::Monday

Many built-in enum types use power of 2 values which allows combining together several values to form a decodable combination of options.

In Decimal => 2, 4, 8, 16...
In Binary => 10, 100, 1000, 10000...

Combination strings can be combined with a Bitwise OR (-bor) or simply pass the values comma delimited which PowerShell is able to parse. So a combined value can be specified like this:

$variable = [Enum.Type] "Value1, Value2"

Display the value of an Enum

# Show the current value of $Season
$Season
You can use the value in a switch statement:

switch ($Season) {
   "Spring" {"It’s Spring"; continue } 
   "Summer" {"It’s Summer"; continue } 
   "Autumn" {"It’s Autumn"; continue } 
   "Winter" {"It’s Winter"; continue } 
}

Winter
It’s Winter

You can access each value as a static property:

PS C:\> [MySeasons]::Spring

To retrieve the integer value we can use ().value__ note that is TWO underscores.

PS C:\> ($Season).value__
3

An alternative way to get the integer value is by casting the variable to int:

PS C:\> [int]$Season
3

To discover the datatype, use the .GetType() method against the variable :

PS C:\> $Season.GetType()

IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     MySeasons    System.Enum

You can also confirm the BaseType with:

PS C:\> $Season -is [System.enum]
True

List all the possible values of an enum datatype using the static method ::GetNames or ::GetValues

PS> [Enum]::GetNames( [MySeasons] )

This can also be used for any of the many built-in enums:
PS> [Enum]::GetNames([Microsoft.Powershell.ExecutionPolicy])

PS> [Enum]::GetNames([System.DayOfWeek])
PS> [Enum]::GetNames([System.Security.AccessControl.FileSystemRights])
PS> [Enum]::GetNames([System.Security.AccessControl.RegistryRights])

List all the names and integer values (see also Get-EnumAndValues.ps1):

PS C:\> [System.Enum]::GetValues([MySeasons]) |
ForEach-Object { [PSCustomObject]@{ValueName = $_; IntValue = [int]$_ } }

Use with Functions/Parameters

When writing a script or function it is common to use a param statement to constrain parameters to a known data type:

[string]$FirstName,
[int]$ProductID

An enum Data Type can be used in the same way to constrain a passed parameter to the predefined enum values:

[MySeasons]$NewSeason

PowerShell ISE will read this enum, and Intellisense can prompt for values from the list.

This is similar to the ValidateSet parameter validation attribute:

[Parameter(Mandatory=$False)]
[ValidateSet('Spring','Summer','Autumn','Winter')]
[string]$NewSeason,

The difference being that the ValidateSet will have to be written (and maintained) in every function that you write. An enum Data Type can be defined just once in a session, script, or module and then re-used.

“Anyone whose needs are small seems threatening to the rich, because he’s always ready to escape their control” ~ Nicolas Chamfort

Related PowerShell Cmdlets

DataTypes - PowerShell data types.
Help: about_Classes


 
Copyright © 1999-2024 SS64.com
Some rights reserved