Enum Week: Listing Enumeration Values

by Sep 27, 2016

This week we are looking at enumerations: what they are, and how you can benefit from them.

In the previous tip we explained how PowerShell converts strings to enumeration values. If you’d like to know what the allowed string values are for a parameter that accepts an enumeration, first take a look at a simple example that changes console foreground colors:

 
PS> $host.UI.RawUI.ForegroundColor = 'Red'

PS> $host.UI.RawUI.ForegroundColor = 'White'

PS>  
 

These commands change the foreground color first to red, then back to white.

How do you know the names of the colors that are supported by the console, though? For this, you need to know the true datatype that ForegroundColor really supports:

 

PS> $host.UI.RawUI.ForegroundColor.GetType().FullName 
System.ConsoleColor
 

The type is “System.ConsoleColor”. Now you can check whether it is really an enumeration:

 
PS> $host.UI.RawUI.ForegroundColor.GetType().IsEnum
True
 

If it is, like in this example, you can list its names:

 
PS> [System.Enum]::GetNames([System.ConsoleColor])
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White
 

Any of these values can be specified to set the console foreground color, and the same strategy applies to any other property or parameter that accepts enumeration values.

Coincidentally, when you submit a value that fits no enumeration name, the exception message will list the names, too.

Twitter This Tip! ReTweet this Tip!