Friday, May 6, 2011

Enumerate your own enum in Powershell

Enumeration does not really exist in Powershell. However, when I wrote my ExportRegistyToFile Powershell script, I use 2 techniques of "enumeration".

1st: easily way using hash
Declaration:

$DataTypes = @{"enum1" = "1"; "enum2" = "2"; "enum3" = "3"}


Enumeration:

$DataTypes.Keys

That display (remember hash is not array, so you can have enum2 before enum1 but you set enum1 before enum2)

enum2
enum1
enum3



Enumerate a key and his value:

$enum = "enum2"
Write-Host "Enum:" $enum "value:" $DataTypes ["$enum"]

which display

Enum: enum2 value: 2


Now, 2nd technique to do an enumeration by using add-type (this is the same technique you use when you want to do a pinvoke for accessing win32 api)
Declaration:

$signature = @"
public enum MyEnum : int {
enum1 = 0x0001,
enum2 = 0x0002,
enum3 = 0x0003
}
"@
$type = Add-Type -TypeDefinition $signature -Name Enum -Namespace Data -Using System.Text -PassThru



Enumeration (with + tips - Namespace.functionname+yourenum)

[Enum]::GetNames([Data.Enum+MyEnum])

which display

enum1
enum2
enum3



Enumerate a key and his value:

$enum = "enum2"
Write-Host "Enum:" ([Data.Enum+MyEnum]::$enum) "value:" ([Data.Enum+MyEnum]::$enum.value__)

which display

Enum: enum2 value: 2



There is a great article on scripting guys blog that explain this last technique
http://blogs.technet.com/b/heyscriptingguy/archive/2010/06/06/hey-scripting-guy-weekend-scripter-the-fruity-bouquet-of-windows-powershell-enumerations.aspx


Below a powershell script to test these 2 techniques (Download it)

#
#
# Enum
#
# by F.Richard 2011-05
#
#

#Requires -Version 2.0

$signature = @"
public enum MyEnum : int {
enum1 = 0x0001,
enum2 = 0x0002,
enum3 = 0x0003
}
"@

# Register Enum functions
If (-not ("Data.Enum" -as [Type])) {
$type = Add-Type -TypeDefinition $signature -Name Enum -Namespace Data -Using System.Text -PassThru
} else {
If ($debug) { Write-Host "Data.Enum already Registered" }
}


[Enum]::GetNames([Data.Enum+MyEnum])
$enum = "enum2"
Write-Host "Enum:" ([Data.Enum+MyEnum]::$enum) "value:" ([Data.Enum+MyEnum]::$enum.value__)


$DataTypes = @{"enum1" = "1"; "enum2" = "2"; "enum3" = "3"}
$DataTypes.Keys
$enum = "enum2"
Write-Host "Enum:" $enum "value:" $DataTypes["$enum"]

No comments: