How to create enum in PowerShell?

[Updated to comply with the naming guidelines (create=>new)]

Dynamic assembly emitting techniques can be used to create new classes or data types in PowerShell. Trick is that right permission needs to be set so that data types created in dynamic assembly can be used subsequently.

Following is an example for creating a new enum type and use it in powershell.

PS> cat enum.ps1

function New-Enum ([string] $name)


    $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 $args.Length; $i++)


        $null = $enumBuilder.DefineLiteral($args[$i], $i);



    $enumBuilder.CreateType() > $null;


PS> . ‘C:\Documents and Settings\gxie\enum.ps1′

PS > New-Enum my.color blue red yellow

PS > [my.color]::blue


PS > [my.color]::red


PS > [my.color]::yellow


PS > [my.color]::black

PS > 

- George from PowerShell Team