Emulate ternary operator in PowerShell

Emulate ternary or conditional operator in PowerShell 5. It takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if…else statement.

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

Leave a Comment