Summary: Ed Wilson, Microsoft Scripting Guy, talks about creating enumerations in Windows PowerShell 5.0.
Microsoft Scripting Guy, Ed Wilson, is here. It is nearly a stealth feature in Windows PowerShell 5.0—there is an Enum keyword. Yep, that's right, there is an Enum keyword. I wonder what it does? Probably has something to do with creating enums.
Is this a big deal? You betcha...as they may say in some places.
Why? Because prior to Windows PowerShell 5.0, you had to basically create an enum by using C# kinds of code, and then adding it as a type. Did it work? Sure it did. Was it Windows PowerShell? Well, in that it actually worked and I wrote it in Windows PowerShell—sure it was Windows PowerShell.
Note For reference, refer to my Hey, Scripting Guy! Blog post The Fruity Bouquet of Windows PowerShell Enumerations.
Before PowerShell 5.0
Before Windows PowerShell 5.0, if I wanted to create an enumeration, I basically wrote inline C# code. Here is an example that creates a simple enumeration that assigns numeric values to three different types of fruit:
$enum = "
public enum fruit
apple = 29, pear = 30, kiwi = 31
Add-Type -TypeDefinition $enum -Language CSharpVersion3
This is pretty cool code, and the fact that I could create a custom enum in a scripting language was pretty wild. I wrote this code in 2010, and it has worked ever since. In fact, nothing has improved in this regards in the past five years–—until Windows PowerShell 5.0 came out in Windows 10.
Use the enum keyword
So, whereas I used to have to create a giant string, with embedded C# code, and then use the Add-Type command to add in C# code, now I have an enum keyword. This makes the code much cleaner, and very easy to use.
I use the enum keyword and assign a name for the enum. I then open and close a script block. This appears here:
Now I simply assign numeric values for each property:
Apple = 29
Pear = 30
Kiwi = 31
When I run my script, it creates the enum. I can then access each property as a static property. This is shown here:
PS C:\Users\mredw> [fruit]::Apple
The cool thing is that IntelliSense pops up and shows the permissible members:
That is all there is to using enumerations in Windows PowerShell 5.0. Join me tomorrow when I will talk about more cool stuff.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at firstname.lastname@example.org, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy