Powershell enum

13
Using enums in Powershell Jason

Transcript of Powershell enum

Page 1: Powershell enum

Using enums in PowershellJason

Page 2: Powershell enum

Enum

Enums are a very useful way to encode "options" in .NET programming.

They offer a mechanism to represent a fixed set of known values, named in a developer-friendly way.

Page 3: Powershell enum

Using enums in Powershell

Let's start examining this support by looking at the DayOfWeek enum.

PS> $now = Get-Date PS> $now.DayOfWeekThursday PS> $now | Get-Member DayOfWeek

TypeName: System.DateTimeName MemberType Definition---- ---------- ----------DayOfWeek Property System.DayOfWeek DayOfWeek {get;}

Page 4: Powershell enum

Possible enum values

PS> [Enum]::GetNames( [System.DayOfWeek] )SundayMondayTuesdayWednesdayThursdayFridaySaturday

Page 5: Powershell enum

Creating enum instances

The most direct way is to use the same "::" syntax used when accessing static .NET 

Another option is to cast a string containing a valid enum name into the enum type:

PS> $enumVal = [System.DayOfWeek]::Monday

PS> $enumVal = [System.DayOfWeek]::Sunday

PS> $enumVal = [System.DayOfWeek] 'Sunday'

Page 6: Powershell enum

Defining new enum types

Let's look at how to define a brand new enum type within your Powershell script

PS> $enumVal = [System.DayOfWeek] 'Sunday'

Add-Type -TypeDefinition @" public enum SimpleEnumType { Value1, Value2, Value3 }"@

PS> [SimpleEnumType]::Value1Value1

Page 7: Powershell enum

Add-Type

The Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session

Page 8: Powershell enum

Add-Type -TypeDefinitionPS>$source = @"public class BasicTest{ public static int Add(int a, int b) { return (a + b); }

public int Multiply(int a, int b) { return (a * b); }}"@

C:\PS> Add-Type -TypeDefinition $source

Page 9: Powershell enum

Add-Type -path

Add-Type -Path C:\Temp\BasicTest.dll

Add-Type -Path C:\Temp\BasicTest.cs

Page 10: Powershell enum

Defining new enum types

If you don't give enum names explicit values, they will be automatically numbered starting from 0.

PS> [SimpleEnumType]::Value1 -as [int]0PS> [SimpleEnumType]::Value2 -as [int]1PS> [SimpleEnumType]::Value3 -as [int]2

Page 11: Powershell enum

Defining new enum types

You can also define specific integer values for each enum value

Add-Type -TypeDefinition @" public enum ExplicitEnumType { None = 0, Value1 = 1, Value2 = 10, Value3 = 100 }"@

PS> [ExplicitEnumType]::Value2 -as [int]10

Page 12: Powershell enum

Defining new enum types

If you want to provide explicit support for bitwise combinations of values

Add-Type -TypeDefinition @“

[System.Flags] public enum FlagsEnumType { None = 0, Value1 = 1, Value2 = 2, Value3 = 4 } "@ PS> [FlagsEnumType] "Value1, Value3"Value1, Value3

Page 13: Powershell enum

Reference

Using enums in Powershell

http://latkin.org/blog/2012/07/08/using-enums-in-powershell/

MSND Add-Type

http://technet.microsoft.com/en-us/library/hh849914.aspx