The flags attribute

By default, an enumeration matches a single value. If the enumeration contains more than one name for a value, the first name will be chosen.

The flags attribute allows a value to describe more than one name. The flags attribute is placed before the enum keyword.

Typically, each value in the enumeration is given a value with a unique bit combination. This is shown in the following enumeration; the bit combination is shown in the comment after the value:

[Flags()]
enum MyEnum {
First = 1 # 001
Second = 2 # 010
Third = 4 # 100
}

Automatic value assignment cannot be reasonably used to assign values for a flags enumeration at the time of writing.

When the flags attribute is present, PowerShell will cast a string that contains two or more names in a comma-separated list to the value that represents that combination:

[Int][MyEnum]'First,Second'

PowerShell will also cast a numeric value into a set of names. A value of 6 can be used to represent the Second and Third flags:

PS> [MyEnum]6
Second, Third

Several enumerations that use the Flags attribute also provide named composite values. For example, the following enumeration contains a name that is used to represent the combination of the first and third flags:

[Flags()]
enum MyEnum {
First = 1 # 001
Second = 2 # 010
Third = 4 # 100
FirstAndThird = 5 # 101
}

As FirstAndThird explicitly matches the value 5, any value the enumeration converts will use the FirstAndThird name instead of the individual values:

PS> [MyEnum]7
Second, FirstAndThird

PS> [MyEnum]'First, Second, Third'
Second, FirstAndThird

The System.Security.AccessControl.FileSystemRights enumeration makes use of this technique to summarise groups of rights. The Modify name can be represented as the 110000000110111111 binary string. The enumeration names that make up the value of Modify may be displayed by comparing individual bits in the value with other possible values of the enumeration. The following snippet isolates each bit in turn and attempts to convert that single bit into a FileSystemRight name:

$value = [Int64][System.Security.AccessControl.FileSystemRights]::Modify
$i = 0
do {
if ($bit = $value -band 1 -shl $i++) {
[System.Security.AccessControl.FileSystemRights]$bit
}
} until (1 -shl $i -ge $value)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.159.10