Powershell enum
-
Upload
learningtech -
Category
Technology
-
view
2.506 -
download
7
Transcript of Powershell enum
Using enums in PowershellJason
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.
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;}
Possible enum values
PS> [Enum]::GetNames( [System.DayOfWeek] )SundayMondayTuesdayWednesdayThursdayFridaySaturday
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'
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
Add-Type
The Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session
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
Add-Type -path
Add-Type -Path C:\Temp\BasicTest.dll
Add-Type -Path C:\Temp\BasicTest.cs
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
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
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
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