Search notes:

PowerShell: Ternary operator

The ternary operator allows to rewrite a simple if ($cond) { $expr_true } else { $expr_false} statement like so (and thus save a few key strokes, the most expensive resource in a programmer's life):
$cond ? $expr_true : $expr_false
Simple example:
$flag = $true

$val = $flag ? 'true' : 'false'

write-output "val  = $val"

Workaround for Unexpected token '?' in expression or statement

The ternary operator was included in (I believe) PowerShell 7.1. In earlier versions, trying to use the ternary operator would fail with the error message Unexpected token '?' in expression or statement..
A workaround in such version sis to use the evaluation value of an if statement:
$flag = $false

$val  = if ($flag) { 'true' } else { 'false' }

write-output "val  = $val"
In some earlier versions of PowerShell Core, it was possible to enable the ternary operator as an experimental operator:
PS C:\> enable-experimentalFeature PSTernaryOperator

See also

operators

Index