6

#PSTip Creating flagged enumerations in PowerShell

At times, we may want to create an enumeration object in which a combination of different constants means different values or descriptions. For example, look at this scripting skill set enumeration:

namespace Scripting
{
    public enum Skill
    {
       Batch = 1,
       VBScript = 2,
       Perl = 4,
       Python = 8,
       PowerShell = 16
    }
}

From the above enumeration, we can derive the skill set value for a person. But, what if we want to derive a set of all scripting skills he/she holds? or what if we want to assign a value to a person to denote that he knows all these scripting languages or skills?

The general enumeration constants won’t let us do this. This is where the FlagsAttribute class will help us. Here is how the MSDN article distinguishes regular enumeration constants from those defined with FlagsAttribute:

Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined with a bitwise OR operation to generate unnamed values, whereas enumerated constants are not. Languages vary in their use of bit fields compared to enumeration constants.

Now that we understand why we need FlagsAttribute, let us see a quick example on how to build these enum objects:

$enum = "
using System;

namespace Scripting
{
     [FlagsAttribute]
     public enum Skill
     {
         Batch = 1,
         VBScript = 2,
         Perl = 4,
         Python = 8,
         PowerShell = 16
     }
}
"
Add-Type -TypeDefinition $enum -Language CSharpVersion3

We can access the enumeration we just created by using the namespace [Scripting.Skill]

This is it. Now, a person who knows all these scripting languages will have an enumeration value of 31.

How do I know that? Let us see that in a subsequent #PSTip. 🙂

Filed in: Columns, Tips and Tricks Tags: , , , ,

6 Responses to "#PSTip Creating flagged enumerations in PowerShell"

  1. Matheus Kamphorst says:

    Great! a i usually use C# objects on my powershell scripts.

  2. vince says:

    Interesting. I wasn’t aware that you could use a string containing c# code and import types…is there a way I can execute a c# string as a program ?

  3. Ben says:

    To get this working in modern Windows without installing .NET 3.5, I changed the last line to:

    Add-Type -TypeDefinition $enum -Language CSharpVersion3

  4. Ben says:

    To get this working in modern Windows without installing .NET 3.5, I changed the last line to:

    Add-Type -TypeDefinition $enum -Language CSharp

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: