Tern around: Concise PowerShell Ternary Operators

Tern around: Concise PowerShell Ternary Operators

  •  
  •  
  •  
  •  
  •  
  •  
4/5 - (1 vote)

I’m writing this down because…

Mark me! A fun drinking game for all! 🍻 : Outlander

I will forget it.

I was reviewing someone else’s code that was largely full of common if/then statements and then stumbled across a solitary instance of a ternary statement.

It took me a while to decipher since the ternary evaluation happened as an argument for a cmdlet–definitely limiting its readability.  So, now that I’ve used the term a few times, what is it?

What is a ternary operator?

It’s a method of evaluating a condition (similar to if/then/else).  A ternary is a coding sequence that follows this pattern:

declaration of a variable/value
@{result if true; result if false}[condition to evaluate]

We’ll take a simple if/else clause:

$radio = "on"
if ($radio -eq "on")
     { 
     Write-Host "The radio is on." 
     }
else 
     { 
     "The radio is off." 
     }

Pretty simple, right?  Easy to read, easy to troubleshoot, and easy to understand.

Now, let’s take that and switch it up with the ternary format.

$radio = "on"
@{ $true = 'The radio is on'; $false = 'The radio is off.'}[$radio -eq "on"]

A bit more complicated to read (especially if you’re not familiar with the construct).

In this example, it did save a few characters of space; depending on how you format your code, it could be a lot of lines.

So, there you have it.

Why would I ever use it?

Since I was in a time crunch when I encountered it (and it’s not terribly common), my personal perspective is that it made the code less legible and took slightly longer to decipher.  Why would someone use it?

  • Code reduction.
  • To look cool: it looks more programmer-esque.

I’m definitely not a programmer.  I’m barely a script writer.  I try to do things that are simple to read and simple to follow–usually because the scripts that I provide will be parted out and chunks used or adapted by other people and then further maintained by more people after that, each with varying levels of proficiency and experience.

It’s of no use to show off your skill as something that machines can read but humans can’t.

But, if you must, then do so.

 

 

Published by Aaron Guilmette

Helping companies conquer inferior technology since 1997. I spend my time developing and implementing technology solutions so people can spend less time with technology. Specialties: Active Directory and Exchange consulting and deployment, Virtualization, Disaster Recovery, Office 365, datacenter migration/consolidation, cheese.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.