Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a enum?

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.

like image 318
float Avatar asked Mar 05 '23 05:03

float


1 Answers

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.

like image 137
Mark Wragg Avatar answered Mar 11 '23 03:03

Mark Wragg