Monday, August 24, 2009

New-Enum for Powershell v2

Recently I wrote about new-enum function that should work both in Posh v1 and v2… Well, it doesn’t, because v1 will throw an error on @Args.

Below is updated version that should work in both powershells:

# Supports creation of custom Enums during runtime. 
# Because CoreFunctions and CustomFunctions requires already some enumerations (specifically LogType), it must be initialized in main script.
function Global:S4M\New-Enum ([string] $name, [switch]$FixMode, [array]$Members = @()) {

$Members += $Args

$appdomain = [System.Threading.Thread]::GetDomain()
$assembly = new-object System.Reflection.AssemblyName
$assembly.Name = "EmittedEnum"
$assemblyBuilder = $appdomain.DefineDynamicAssembly($assembly,
[System.Reflection.Emit.AssemblyBuilderAccess]::Save -bor [System.Reflection.Emit.AssemblyBuilderAccess]::Run);
$moduleBuilder = $assemblyBuilder.DefineDynamicModule("DynamicModule", "DynamicModule.mod");
$enumBuilder = $moduleBuilder.DefineEnum($name, [System.Reflection.TypeAttributes]::Public, [System.Int32]);

for($i = 0; $i -lt $Members.Length; $i++) {
If (([string]($Members[$i])).Contains("=")) {
[string]$EnumName = [string](($Members[$i].Split("="))[0])
$Null = $enumBuilder.DefineLiteral($EnumName, [int]($Members[$i].Split("="))[1]);
} Else {
$Null = $enumBuilder.DefineLiteral($Members[$i], $i);

$enumBuilder.CreateType() > $Null;

#Used to fix issue with Powershell v2
If ($Host.Version.Major -eq 1 -or $FixMode) {
$enumBuilder.CreateType() > $Null;
} Else {
S4M\New-Enum -FixMode -Name $name -Members $Members
$enumBuilder.CreateType() > $Null;

No comments: