January 23rd, 2007

How to create enum in PowerShell?

PowerShell Team
PowerShell Team

[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

blue

PS > [my.color]::red

red

PS > [my.color]::yellow

yellow

PS > [my.color]::black

PS > 

– George from PowerShell Team

 

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.