PowerShell 5.0

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]Code language: PowerShell (powershell)

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"
falseCode language: PowerShell (powershell)

Jan Reilink

Hi, my name is Jan. I am not a hacker, coder, developer or guru. I am merely an application manager / systems administrator, doing my daily thing at Embrace - The Human Cloud. In the past I worked for clidn and Vevida. With over 20 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization. I blog at https://www.saotn.org.