Skip to content

Instantly share code, notes, and snippets.

@turboBasic
Last active September 8, 2017 07:54
Show Gist options
  • Save turboBasic/ee838907399082b4f94fa91fadc495af to your computer and use it in GitHub Desktop.
Save turboBasic/ee838907399082b4f94fa91fadc495af to your computer and use it in GitHub Desktop.
[Get Enum values] Get all possible values of Enum type. Answers question "How do I get all possible values of variable of Enum type when the type is not known?" #powershell
# Get all possible values of variable of dynamic Enum type
function Get-EnumInformation( [Object] $thing ) {
if( $thing -is [Enum] ) {
$type = $thing.getType()
} elseif( ($thing -as [Type]).baseType.fullName -eq 'System.Enum' ) {
$type = $thing -as [Type]
} else {
return $null
}
[PSCustomObject] @{
Type = $type.fullName
UnderlyingType = [Enum]::getUnderlyingType($type).fullName # or $type.getUnderlyingType().fullName
EnumElementNames = [Enum]::getNames($type) # or $type.getEnumNames()
EnumElementValues = [Enum]::getValues($type) # or $type.getEnumValues()
EnumElementNamesString = [Enum]::getNames($type) -join ', '
}
}
or
$VerbosePreference.GetType().GetEnumValues()
# or if you start with name of type in string and you need to cast to that type explicitly:
$String = 'System.Management.Automation.ActionPreference'
$Value = 'SilentlyContinue'
# ...
$Value -As ($String -As [Type])
# or at least in Powershell 5 even simpler:
$Value -As $String
$Value -As 'System.Management.Automation.ActionPreference'
'SilentlyContinue' -As 'System.Management.Automation.ActionPreference'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment