Simplify Conditional Logic with PowerShell Ternary Operators

Published:26 June 2019 - 1 min. read

The if/then construct is commonplace in PowerShell code but did you know there’s another way called the ternary operator that allows you to make your if/then constructs much more concise? Let’s learn how to build a custom PowerShell ternary operator.

At the expense of readability, some say, the ternary operator builds conditional logic that’s more concise, simpler, and with less code. They’re correct but it’s just so nice to have that ternary-like behavior in PowerShell!

If you’re not familiar with a ternary operator, it’s basically using a hashtable or similar construct to make a conditional decision based on criteria.

If/Then in PowerShell

To explain the Powershell ternary operator, let’s first start off with an example of an if/then construct.

$CarColor = 'Blue'
if ($CarColor -eq 'Blue') {
    'The car color is blue'
} else {
    'The car color is not blue'
}

At first glance, you might not think there’s anything wrong with it. In fact, there really isn’t but this condition could be tested just as easily with a single line (under my personal limit of 115 characters).

Now build a PowerShell hashtable with two keys; $true and $false. Then, make the values what you’d like to be displayed if a condition you define is met.

@{ $true = 'The car color is blue'; $false = 'The car color is not blue' }
[$CarColor -eq 'Blue']

Next, define the condition ($CarColor is Blue) and check to see if that condition is met with $CarColor -eq 'Blue'.

$CarColor = 'Blue'
@{ $true = 'The car color is blue'; $false = 'The car color is not blue'}
$CarColor -eq 'Blue'

Now use the condition ($CarColor -eq 'Blue') as a key in that hashtable. Doing this performs the check and then uses the result to look up the key in the hashtable.

Finishing off the PowerShell Ternary Operator

$CarColor = 'Blue'
@{ $true = 'The car color is blue'; $false = 'The car color is not blue'}[$CarColor -eq 'Blue']
A custom PowerShell ternary operator
A custom PowerShell ternary operator

One line! Isn’t that much more succinct? Instead of using an if/then statement I’m using a hashtable and performing a lookup based on if $CarColor equals Blue or not. The resulting index is then output to the console. If you’d like to use this method, it’s just as simple as filling in these blanks:

@{$true = $ResultyouwanttodoifTrue; $false = $ResultyouwantifFalse}[]

You could also include more than just $true and $false if you’d like. You could add any number of conditions in the hashtable and check for them. It’s an easy way to replace long if/then statements or switch statements.

You now have a custom PowerShell ternary operator you can start using in your scripts today!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!