This morning I did a little exercise. Because PowerShell does not have C#'s Using Statement, Class references have to be fully qualified. This includes Enumeration Values. IMHO, this can make calls to managed methods a bit wordy.
In order to manage this, I have at times initialized a hash table with enumeration values. For example, to initialize the values of System.Security.Cryptography.CipherMode I would create the following.
$CipherMode
= @{}
$CipherMode.OFB = [System.Security.Cryptography.CipherMode]::OFB
$CipherMode.CFB = [System.Security.Cryptography.CipherMode]::CFB
$CipherMode.CBC = [System.Security.Cryptography.CipherMode]::CBC
$CipherMode.ECB = [System.Security.Cryptography.CipherMode]::ECB
$CipherMode.CTS = [System.Security.Cryptography.CipherMode]::CTS
This allows use of
$CipherMode.CBC instead of
[System.Security.Cryptography.CipherMode]::CBC. While I found this handy at times, it is arduous to initialize. And this one only has 5 values.
I developed a couple of functions that take the drudgery out of it. The usage is:
$CipherMode
= Get-EnumValues "System.Security.Cryptography.CipherMode"
This as easily handles enumeration of 2 or 200. Beauty!
I also made a helper function that will simply show me the enumeration names:
Get-EnumNames
"System.Security.Cryptography.CipherMode"
This will return:
CBC
ECB
OFB
CFB
CTS
The Source Code is as follows:
function
Get-ValidEnumClass ([string] $ClassName = ${Throw "Class Name is required"})
{
$type = [System.Type]::GetType($ClassName)
if ($type -eq $null)
{
throw "Invalid Class Name or Assembly not loaded for [$ClassName]"
}
if (!$type.IsEnum)
{
throw "Invalid Enum Class [$ClassName]"
}
$type
}
function
Get-EnumNames ($EnumClass = ${Throw "Valid Enum Class Name or Type is required"})
{
if ($EnumClass -is [string])
{
$EnumClass = Get-ValidEnumClass $EnumClass
}
[System.Enum]::GetNames($EnumClass)
}
function
Get-EnumValues ([string] $EnumClassName = ${Throw "Valid Enum Class Name is required"})
{
$type = Get-ValidEnumClass $EnumClassName
$enumNames = Get-EnumNames $type
$values = @{}
foreach ($name in $enumNames)
{
$values[$name] = $type::$name.GetHashCode()
}
$values
}