Wednesday, 1 January 2014

PowerShell enumerated types

The following code shows how to create your own enumerated types and a possible way of using the type.

$myenum = "
   Namespace myspace
   {
      public enum cards
      {
         hearts,
         clubs,
         diamonds,
         spades
      }
   }
";

try {
  [myspace.cards]
} catch {
  Add-Type -TypeDefinition $myenum -Language CSharpVersion3;
}

Write-Host "Assigning fred an enum value";
$fred=[myspace.cards]::hearts;

switch ($fred)
{
    ([myspace.cards]::hearts) {"Fred is now hearts"; Break}
    ([myspace.cards]::clubs) {"Fred is now clubs"; Break}
    ([myspace.cards]::diamonds) {"Fred is now diamonds"; Break}
    ([myspace.cards]::spades) {"Fred is now spades"; Break}
}

Write-Host "All done now!";
The try/catch block is used to avoid the error: Add-Type : Cannot add type. The type name 'myspace.cards' already exists. At line:1 char:1 + Add-Type -TypeDefinition $myenum -Language CSharpVersion3; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (myspace.cards:String) [Add-Type], Exception + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand if the assembly is already loaded. A namespace is used in the creation of this enum because as the documentation reminds us:
Include a namespace declaration in your type definition. If you omit the namespace declaration, your type might have the same name as another type or the shortcut for another type, causing an unintentional overwrite. For example, if you define a type called "Exception", scripts that use Exception" as the shortcut for System.Exception will fail.


The following code can be used to look at the definitions for the enumerated type.

foreach ($m in [System.Enum]::GetValues([ConsoleColor]))
{ Write-Host ([int]$m): $m }


Keywords: powershell enum namespace

No comments:

Post a Comment