concept enum in category powershell

appears as: n enum, enum, enums, The enums
Windows PowerShell in Action, Third Edition

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.

An enum type in .NET is a way of creating a fixed set of name-value constants. The ability to define these types is missing from PowerShell prior to version 5.0 (see chapter 19), but you can work around this by using Add-Type. You’ll define an enum that can be used to specify a coffee order. You’ll constrain the types of coffee orders you’ll allow to Latte, Mocha, Americano, Cappuccino, or Espresso. First, set a variable to the list of drink types:

PS> $beverages = 'Latte, Mocha, Americano, Cappuccino, Espresso'

Pass a string to Add-Type that contains the fragment of C# needed to define an enum type:

The .NET framework provides a user-definable data type related to classes called an enumeration (usually shortened to enum) that defines a closed set of named constant values. For example, there’s a predefined enum type in the .NET framework for the days of the week, which you can access using a number or a name:

Let’s look at how you can create your own enums in PowerShell. Use the enum keyword to define the start of the enum. Supply a name and the list of values, and it’s done:

PS> enum foo { one; two; three }

As before, you can access the enum using numerical values, a static member reference, or a cast:

PS> [foo] 0
one

PS> [foo] "one"
one

PS> [foo]::one
one

Note that we didn’t specify any values when we defined the enum. If no explicit values are provided, the compiler assigns integer values in order, starting at 0. Specifying explicit values looks like this:

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest