How to convert a string to a enum?

南楼画角 提交于 2021-02-09 05:43:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!