问题
I'm trying to convert a string to a enum value in PowerShell but couldn't find this anywhere...
I'm getting a JSON result, where I only want to consume the Healthstate which is defined as a string.
enum HealthState
{
Invalid = 0
Ok = 1
Warning = 2
Error = 3
Unknown = 65535
}
$jsonResult = "Ok"
$HealthStateResultEnum = [Enum]::ToObject([HealthState], $jsonResult)
Thanks in advance.
回答1:
You can simply cast the string result as the Enum type:
$HealthStateResultEnum = [HealthState]$jsonResult
This will work whether $jsonResult
contains a string or value from the enum type.
回答2:
Assuming you want to get the value__ of the enum:
PS> [Enum]::GetValues([HealthState])|? {$_ -eq $JSonresult}|Select @{n="Name";e={"$_"}},value__
Name value__
---- -------
Ok 1
Or simply
PS> [int]([HealthState]$jsonResult)
1
来源:https://stackoverflow.com/questions/52889230/how-to-convert-a-string-to-a-enum