PowerShell 5.0 logo

Emulate ternary operator in PowerShell

PowerShell ternary operator emulation for PowerShell 5.1. Quick and dirty determine if a condition is true or false by emulating the ternary operator. For example when determinering if the server you are servicing is a Windows Server Desktop Experience version or not (and thus Server Core).

Home » Windows Server » Emulate ternary operator in PowerShell

Quickly and dirty determine if a condition is true or false in PowerShell 5.1 by emulating the ternary operator. For example when determinering if the server you are servicing is a Windows Server Desktop Experience version or not (and thus Server Core):

$condition = (Get-CimInstance Win32_OptionalFeature | Where-Object Name -eq 'Server-Gui-Mgmt').InstallState ({true}, {false})[!$condition]

This returns true for a GUI enabled Windows Server instance and false for Windows Server Core.

Source: Stack Overflow “Ternary operator in PowerShell” comment by Roman Kuzmin.

And yes, PowerShell Core 7 (pwsh) supports it natively:

(Get-CimInstance Win32_OptionalFeature | Where-Object Name -eq 'Server-Gui-Mgmt').InstallState ? "true" : "false"
false
Jan Reilink
Jan Reilink

In my day to day work, I’m a systems administrator – DevOps / SRE and applications manager at Embrace – The Human Cloud. At Embrace we develop, maintain and host social intranets for our clients. Provide digital services and make working more efficient within various sectors.

Read why we can use your help and support ❤️

Articles: 173