익명 09:43

Listing `value__` enums in PowerShell

Listing `value__` enums in PowerShell

The PowerShell scripts I write have to be as compatible as possible, so when checking for states of things I always prefer to poll an enum (4) rather than a string (Enabled). In 99% of cases the string value remains consistent even on localised versions of Windows, but there will always be one device where it isn't, and it'll be the one running my script and getting me in trouble. This is fine as long as I know what the enums map to, but getting that information is like pulling teeth.

Example: Services
Googling "service state enum powershell" leads you here, where you can see a nice table listing the values for a service's state which lines up to the value you get from performing (get-service 'xyz').status.value__. This allows me to say
if ($value -eq 1) as opposed to if ($value -eq 'enabled'), which is a vastly more robust comparison.
Again, fine, if you know the terms to search for.

The actual question
Is there some PowerShell command or a website I can use to list these value__ enums? Right now I'm trying to find the enum for the state value from get-WindowsOptionalFeature and I'm pulling nothing. Surely it's not meant to be this scattershot? I'm self-taught, so I'm hoping there's some repository of this stuff which is common knowledge that I just glazed over.



Top Answer/Comment:

Its possible to view the possible values yes.

$feature = Get-WindowsOptionalFeature -Online | Select-Object -First 1
$feature.State | Get-Member

At the top of the output it says TypeName: Microsoft.Dism.Commands.FeatureState

The following command will give you the list of possible values as an array

[enum]::getValues([Microsoft.Dism.Commands.FeatureState]) | % {"{0} = {1}" -f [int]$_,$_}

Which will result in:

0 = Disabled
1 = DisablePending
2 = Enabled
3 = EnablePending
4 = Superseded
5 = PartiallyInstalled
6 = DisabledWithPayloadRemoved

And you can use the index instead of the string.

Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq 0 } 

You can also use the enum directly

Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq [Microsoft.Dism.Commands.FeatureState]::Disabled }
상단 광고의 [X] 버튼을 누르면 내용이 보입니다