header image

Ternary operator

Posted by: | September 25, 2019 Comments Off on 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’}


Using a ternary operator this becomes

PS> $a -gt $b ? ‘Greater’ : ‘Not 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.

under: PowerShell 7

Comments are closed.