New-Enum

The code below allows creation of .NET enumerations in PowerShell without using Add-Type.

Before an Enum can be created a Dynamic Assembly and Module must be created. The function below creates the module in a global variable called DefaultDynamicAssembly. Attempting to retrieve the module builder dynamically returns an InternalModuleBuilder class.

Once the dynamic module is created, any number of Enums can be created from hash tables.

The last example below shows how the functions can be used once they have been loaded.

New-DynamicModuleBuilder "Indented"
$FlagFields = @{
    Bit1 = 1
    Bit2 = 2
    Bit3 = 4
    Bit4 = 8
}
$SimpleValues = @{
    Value1 = 1
    Value2 = 2
}
New-Enum "Indented.Flags" -Flags -Members $FlagFields
New-Enum "Indented.Simple" -Members $SimpleValues
[Indented.Flags]7
[Indented.Simple]1
New-Enum
Share this