Managing Bit Flags (Part 2)

by Mar 6, 2017

In the previous tip we illustrated how you can use PowerShell 5’s new enums to easily decipher bit flags, and even test for individual flags.

If you cannot use PowerShell 5, in older PowerShell versions, you can still use this technique. Simply define the enum via C# code:

# this is the decimal we want to decipher
$rawflags = 56823


# define an enum with the friendly names for the flags
# don't forget [Flags]
# IMPORTANT: you cannot change your type inside a PowerShell session!
# if you made changes to the enum, close PowerShell and open a new
# PowerShell!
$enum = '
using System;
[Flags]
public enum BitFlags 
{
    None    = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Option4 = 8,
    Option5 = 16,
    Option6 = 32,
    Option7 = 64,
    Option8 = 128,
    Option9 = 256,
    Option10= 512,
    Option11= 1024,
    Option12= 2048,
    Option13= 4096,
    Option14= 8192,
    Option15= 16384,
    Option16= 32768,
    Option17= 65536
}
'
Add-Type -TypeDefinition $enum

# convert the decimal to the new enum
[BitFlags]$flags = $rawflags
$flags

# test individual flags
$flags.HasFlag([BitFlags]::Option1)
$flags.HasFlag([BitFlags]::Option2)

As you can see, converting a decimal to your new enum type works well and is very easy:

 
PS C:\> [BitFlags]6625
Option1, Option6, Option7, Option8, Option9, Option12, Option13

PS C:\>  
 

Twitter This Tip! ReTweet this Tip!