Monthly Archive

Categories

Ternary operator

PowerShell v7 preview 4 adds a Ternary operator to PowerShell.

 

A ternary operator is a way to provide shortened coding for a simple if-else block. Its an operator that takes three operands rather than the usual two hence the name ternary.

for example

PS> $a = 5
PS> $b = 3
PS> if ($a -gt $b){'Greater'}else{'Not greater'}
Greater

 

Using a ternary operator this becomes

PS> $a -gt $b ? 'Greater' : 'Not greater'
Greater

 

The generic form is

<condition> ? <value if true> : <value if false>

 

The ternary operator is an experimental feature so needs to be enabled

PS> Enable-ExperimentalFeature PSTernaryOperator

 

and PowerShell restarted.

 

If I use the new operator I think its going to be when I’m working interactively. For scripts and modules I prefer to use the more verbose if statement as its easier to read and understand.

Comments are closed.