Enum Week: Enums in PowerShell 5

by Sep 30, 2016

Requires PowerShell 5 or better

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

Beginning in PowerShell 5, you can create your own enumerations using the keyword “Enum”. This way, users can specify clear-text names instead of cryptic numbers.

 
#requires -Version  5.0 
 
Enum ComputerType
{
  ManagedServer
  ManagedClient
  Server
  Client
}
 
function Connect-Computer 
{
  param 
  (
    [ComputerType] 
    $Type, 
 
    [string] 
    $Name 
  )
 
  "Computername: $Name Type: $Type" 
}
 

When you run this code and then call the function “Connect-Computer”, PowerShell automatically provides IntelliSense for your enumeration values, and only accepts the values listed in the enumeration.

 
PS C:\> Connect-Computer -Type Client -Name Test
Computername: Test Type: Client

PS C:\>
 

Twitter This Tip! ReTweet this Tip!