次の方法で共有


PowerShell Tip: Getting enum values as names, int and bit

There are a number of samples how to resolve enums and display all the possible values. However, none of those worked for me with the enum System.Security.AccessControl.FileSystemRights. This enum has duplicate values and as most functions listing enum values are based on Enum.GetValues, you see not just the duplicate values but also duplicate names. So while sitting in an airplane in Cologne waiting for the staff to fix some valve, i couldn’t think of a better way to spend my time than writing about this world-changing code snippet.

To solve that, I have created this little helper function, an ideal candidate for your PowerShell profile. It uses Enum.GetNames hence shows the names as defined in the enum regardless if they have the same value. Get-Enum prints the binary values if you pass in a Flags enum. If the enum is not a binary one, the output will be only name and value.

[code lang="powershell"]
function Get-Enum {
param (
[type]$Type
)

if ($Type.BaseType.FullName -ne 'System.Enum')
{
Write-Error "Type '$Type' is not an enum"
return
}

if ($Type.CustomAttributes | Where-Object { $_.AttributeType -eq [System.FlagsAttribute] })
{
Write-Host "Type '$Type' is a Flags enum"
Write-Host
$isFlagsEnum = $true
}

$props = @(
@{ Name = 'Name'; Expression={ [string]$_ } }
@{ Name = 'Value'; Expression={ [uint32](Invoke-Expression "[$($type.FullName)]'$_'") }}
)

if ($isFlagsEnum)
{
$props += @{ Name = 'Binary'; Expression={[Convert]::ToString([uint32](Invoke-Expression "[$($type.FullName)]'$_'"), 2)}}
}

[enum]::GetNames($Type) |
Select-Object -Property $props
}

 

You can call the function like this

[code lang="powershell"]
Get-Enum System.DayOfWeek

to get this output:

[code]
Name Value
---- -----
Sunday 0
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
Friday 5
Saturday 6

 

And this is the example of the enum that made me write this post

[code lang="powershell"]
Get-Enum -Type System.Security.AccessControl.FileSystemRights

And as this is a flags enum, the function displays the binary representation of the value as well:

[code]
Name Value Binary
---- ----- ------
ListDirectory 1 1
ReadData 1 1
WriteData 2 10
CreateFiles 2 10
CreateDirectories 4 100
AppendData 4 100
ReadExtendedAttributes 8 1000
WriteExtendedAttributes 16 10000
Traverse 32 100000
ExecuteFile 32 100000
DeleteSubdirectoriesAndFiles 64 1000000
ReadAttributes 128 10000000
WriteAttributes 256 100000000
Write 278 100010110
Delete 65536 10000000000000000
ReadPermissions 131072 100000000000000000
Read 131209 100000000010001001
ReadAndExecute 131241 100000000010101001
Modify 197055 110000000110111111
ChangePermissions 262144 1000000000000000000
TakeOwnership 524288 10000000000000000000
Synchronize 1048576 100000000000000000000
FullControl 2032127 111110000000111111111

Have fun!