ayseff
5/28/2015 - 2:01 PM

Flags Enum without explicit values

Flags Enum without explicit values

# Add an enum with All constant
Add-Type -TypeDefinition @'
    using System;

    [Flags]
    public enum EnumSample
    {
        One,
        Two,
        Three,
        Four,
        Five,
        All = One | Two | Three | Four | Five
    }
'@

[EnumSample]'Four,Five'                       # All
[EnumSample]::Four.HasFlag([EnumSample]::Two) # True
[EnumSample]'Two,Three'                       # Four

# Displaying the problem.  Flags enum are supposed to have each "flag" as a power of two, eg
# 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, etc.  When you let the enum choose its own values,
# even with the [Flags] attribute applied, that doesn't happen.

foreach ($name in [Enum]::GetNames([EnumSample]))
{
    [pscustomobject] @{
       Name  = $name
       Value = [EnumSample]::$name.value__
       Hex   = '0x{0:X8}' -f [EnumSample]::$name.value__
    }
}