Skip to the main content.

PowerShell Tips

Using enumerations in PowerShell (1/2)

Table of contents


Post Featured Image

Tobias & Aleksandar's tip #1:

The two very well-known PowerShell experts have teamed up to share their best and most helpful PowerShell tips.

We will be publishing their scripts over the course of Scriptember in 13 blog posts. Don't miss their insights! Be sure to follow all Scriptember events, listed in our calendar here

 

 

Using enums in PowerShell

Class support was added to PowerShell in 2016 but is still not widely adopted – event though it can be very simple and very powerful.

Often scripts use simple numbers that can be cryptic, hard to understand, and error-prone:


# unstructured
$logLevel = 3

Enums are a perfect strategy to manage lists of values and provide friendly names to them:


# strictly-typed
enum MyLogLevel
{
No
Info
Verbose
Debug
All
}
$logLevel = [MyLogLevel]::Info
$logLevel
if ($logLevel -eq 'Info') { "INFO active" }

Internally, each enum is still a number, but user-friendly names help to understand the purpose, and the enum ensures that only valid numbers can be used:

  • PS C:\> [MyLogLevel]::Info -as [int]
     


Once you start using enums, this also improves usability. PowerShell automatically turns enums into IntelliSense menus. Here is a function called Write-LogMessage that illustrates this:


enum MyLogLevel
{
No
Info
Verbose
Debug
All
}

function Write-LogMessage
{
[CmdletBinding()]
param
(
[string][Parameter(Mandatory)]$Message,
[MyLogLevel]$logLevel = 'Info'
)
'{0:yyyyMMddHHmmss} {1,-7} {2}' -f (Get-Date), $logLevel, $Message
}

Part two of using enumerations in PowerShell is online, too. Click here to read tip #2!

 

Good2know


Scriptember! Stay tuned:

During Scriptember, our calendar provides the best possible overview.  

Scriptember - hier ist die Übersicht

 

  • Follow us on social media, look for and use the hashtags #Scriptember and #PowerShell.
  • Join our live sessions, overview soon here.
  • Participate in challenges and contests. 
  • Share your knowledge.

 

Find all events here!

 

 

 

Related links 

Related posts

7 min read

Hidden configuration variables in PowerShell

Tobias & Aleksandar's tip #13:

The two very well-known PowerShell experts have teamed up to share their best and most...

4 min read

Hiding confirmations in PowerShell

Tobias & Aleksandar's tip #12:

The two PowerShell experts have teamed up to share their best and most helpful...

4 min read

URL Encoding in PowerShell

Tobias & Aleksandar's tip #11:

The two very well-known PowerShell experts have teamed up to share their best and most...

About the author: