PowerShell Enum and Constants: Define Fixed Value Sets

PowerShell Enum and Constants: Define Fixed Value Sets

PowerShell Tips Editor 3 min read
PowerShell Enum and Constants: Define Fixed Value Sets

A parameter that only accepts North, South, East, or West and rejects everything else at the call site — that’s what enums give you. PowerShell enum types enforce a fixed set of valid values, eliminating the string comparison bugs that come from free-form text parameters. This post covers using .NET enums that already exist, creating your own enums with Add-Type, using them in function parameters, and working with flag-style bitmasked enums.

Using .NET Enums in PowerShell

.NET ships with hundreds of enums that PowerShell surfaces directly. You can use them by their full type name and access members with :: notation.

# Use the DayOfWeek enum
[System.DayOfWeek]::Monday
[System.DayOfWeek]::Friday

# Use in a comparison
(Get-Date).DayOfWeek -eq [System.DayOfWeek]::Saturday

# Get the underlying integer value
[int][System.DayOfWeek]::Wednesday   # Returns 3

# Cast integer back to enum
[System.DayOfWeek]2   # Returns Tuesday
# Common useful .NET enums
[System.ConsoleColor]::Red          # Color values
[System.Net.HttpStatusCode]::OK     # HTTP status codes
[System.IO.FileMode]::Append        # File modes

Enumerate Enum Values

Use [System.Enum]::GetValues() or [System.Enum]::GetNames() to list all members of any enum type. This is useful for documentation and validation.

# Get all values of an enum
[System.Enum]::GetValues([System.DayOfWeek])
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
# Get names and their integer values
[System.Enum]::GetValues([System.ConsoleColor]) | ForEach-Object {
    "$_  =  $([int]$_)"
}

Define Custom Enum with Add-Type

Create your own enum type with Add-Type and inline C# code. Once defined, the type is available for the rest of the session.

Add-Type -TypeDefinition @'
public enum Environment {
    Development = 0,
    Staging     = 1,
    Production  = 2
}
'@

# Use the custom enum
$env = [Environment]::Production
Write-Output "Deploying to: $env ($([int]$env))"
Deploying to: Production (2)
Add-Type -TypeDefinition @'
public enum LogLevel {
    Debug   = 0,
    Info    = 1,
    Warning = 2,
    Error   = 3,
    Fatal   = 4
}
'@

Use Enum in Function Parameter

Declaring a parameter as an enum type means PowerShell automatically validates input and provides tab completion — the caller can only pass valid enum members.

function Deploy-Application {
    param(
        [Parameter(Mandatory)]
        [string]$AppName,

        [Parameter(Mandatory)]
        [Environment]$TargetEnvironment
    )

    Write-Output "Deploying $AppName to $TargetEnvironment"

    if ($TargetEnvironment -eq [Environment]::Production) {
        Write-Warning "Production deployment — additional approval required"
    }
}

# Valid calls
Deploy-Application -AppName "WebApp" -TargetEnvironment Production
Deploy-Application -AppName "WebApp" -TargetEnvironment Staging

# Invalid call — throws error automatically
# Deploy-Application -AppName "WebApp" -TargetEnvironment "InvalidEnv"

Switch Statement with Enum

Enums pair naturally with switch statements, making branching on categorical values clean and exhaustive.

function Get-ConnectionString {
    param([Environment]$Env)

    switch ($Env) {
        ([Environment]::Development) { "Server=dev-sql;Database=AppDB_Dev;" }
        ([Environment]::Staging)     { "Server=stg-sql;Database=AppDB_Stg;" }
        ([Environment]::Production)  { "Server=prod-sql;Database=AppDB;" }
        default                      { throw "Unknown environment: $Env" }
    }
}

Get-ConnectionString -Env Staging

Enum Flags for Bitmasked Values

Flag enums use powers-of-two values and the [Flags] attribute, allowing multiple values to be combined with bitwise OR. This is how Windows file attributes and permissions work.

Add-Type -TypeDefinition @'
[System.Flags]
public enum Permissions {
    None    = 0,
    Read    = 1,
    Write   = 2,
    Execute = 4,
    Full    = 7
}
'@

# Combine flags with bitwise OR
$userPerms = [Permissions]::Read -bor [Permissions]::Write
Write-Output "Permissions: $userPerms"   # Read, Write

# Test a specific flag
$hasWrite = ($userPerms -band [Permissions]::Write) -eq [Permissions]::Write
Write-Output "Can write: $hasWrite"

Common Errors and Fixes

  • Enum name collision if same name defined twice: Add-Type throws an error if you try to define a type that already exists in the session — the same type name in the same namespace. Wrap your Add-Type call in a type existence check: if (-not ("Environment" -as [type])) { Add-Type ... }. This makes scripts idempotent in sessions where you run them repeatedly.
  • String to enum cast not automatic in all contexts: Passing the string "Production" where an [Environment] is expected works for function parameters (PowerShell converts automatically), but not in all contexts. If you receive a string from user input or a config file and need an enum, use [Environment]::Parse([Environment], "Production") or "Production" -as [Environment] for safe conversion.

Related Cmdlets / See Also

Wrapping Up

Enums transform free-text string parameters into validated, tab-completable, self-documenting values — the kind of change that prevents an entire category of runtime errors. As a next step, identify any function in your scripts that uses a string parameter restricted to a known set of values (like environment names, log levels, or action types) and convert it to an enum parameter.

Send-Item -To