How to Use Enum in PowerShell

Enum Definition

In PowerShell, Enum or Enumeration is a data type that consists of named constants. Each of constants represents a value whose underlying type is integral numeric type.

Benefits of Enum

There are some benefits of using Enum:

  • Improved readability: Enums make your code more self-explanatory by assigning meaningful names to a set of related values. This can make your code easier to understand and maintain.
  • Strongly-typed code: Enums are strongly-typed, which means the compiler checks the type correctness of assignments and comparisons. This helps catch errors early during the compilation process.
  • IntelliSense support: Many IDE or text editor typically provides IntelliSense support. This means you get autocompletion suggestions and tooltips when using Enums, reducing the possibility of making errors.

How to Use Enum

To define an Enum in PowerShell, you can use the enum keyword followed by the enumeration name and a pair of curly braces enclosing the enumeration values:


enum Color {
    Red
    Green
    Blue
}

In this example, we define an Enum named Color with three enumeration values: Red, Green, and Blue.

To use the Enum, simply refer to the Enum type and its values using the double-colon (::) operator:


$color = [Color]::Green

Here is a more complex example:


enum ErrorCode {
    NotFound = 404
    BadRequest = 400
    InternalServerError = 500
}

function Get-HttpStatusDescription {
    param ([ErrorCode] $ErrorCode)

    switch ($ErrorCode) {
        ([ErrorCode]::NotFound) { return "Not Found" }
        ([ErrorCode]::BadRequest) { return "Bad Request" }
        ([ErrorCode]::InternalServerError) { return "Internal Server Error" }
    }
}

$errorCode = [ErrorCode]::NotFound
$description = Get-HttpStatusDescription -ErrorCode $errorCode
Write-Host "Error Code: $errorCode, Description: $description"

In this example, we define an Enum called ErrorCode for HTTP status codes. We then use the Enum in a function called Get-HttpStatusDescription that takes an ErrorCode as a parameter and returns its description.