Ternary Operator: A Simpler If/Then Conditional Logic in PowerShell

Adam Bertram

Read more posts by this author.

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?

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 (guide.freecodecamp.org), it’s basically using a hashtable or similar construct to make a conditional decision based on criteria.

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 PowerShel 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 lookup the key in the hashtable.

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

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.

Subscribe to Stay in Touch

Never miss out on your favorite ATA posts and our latest announcements!

Looks like you're offline!