Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Understanding the PowerShell 7 Ternary Operator

Posted on October 11, 2019October 11, 2019

I've been writing about and teaching PowerShell from the very beginning. My focus has always been on making it easier for IT Pro to use PowerShell in their daily work to make life easier and to advance their careers. This focus has undoubtedly been challenging as the language has evolved over the years. With PowerShell 7, that is going to continue. Microsoft is adding many new features to the next version of PowerShell.  It seems to me that many of these features are designed to meet Microsoft's needs.  One thing that is becoming clearer to me with each new release is that PowerShell is now many things to many people. It is like the proverbial elephant described by a group of blind men; it means something different depending on what you are touching.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

Meet the Ternary Operator

One of the additions to the latest PowerShell 7 preview is the ternary operator. If your background is like mine, you are saying, "The Whatery?" According to Wikipedia, this is a well-established computer science term.  The operator allows for creating a concise conditional statement.

<if some condition is true> ? <this>:<else this>

Using this operator in PowerShell 7 means, you can write a PowerShell expression like this:

$IsWindows ? "ok":"not ok"

image

The traditional If statement alternative would be:

if ($IsWindows) {
    "ok"
}
else {
    "not ok"
}

In some regards, the ternary operator is not that complicated to figure out. Although there is one major difference. When using an If statement, the Else clause is completely optional. When using the ternary operator the conditional Else component is required.

Here's a traditional If/Else statement.

if ($IsWindows) {
    Get-CimInstance -ClassName win32_service -filter "name='bits'"
}
else {
    Write-Warning "This command requires Windows"
}

Using the new ternary operator you would write it like this:

$IsWindows ? (Get-CimInstance -ClassName win32_service -filter "name='bits'") : (Write-Warning "This command requires Windows")

image

The ternary operator appears to be handy for simple conditional statements. Consider this traditional code.

if ($IsWindows) {
    Get-CimInstance -ClassName win32_service -filter "name='bits'"
    Get-CimInstance -ClassName win32_service -filter "name='wsearch'"
}
else {
    Clear-Host
    Get-Date
    Write-Warning "This command requires Windows"
}

Compared to the ternary operator version.

$IsWindows ? (Get-CimInstance -ClassName win32_service -filter "name='bits'"), (Get-CimInstance -ClassName win32_service -filter "name='wsearch'") : (Clear-Host),(Get-Date),(Write-Warning "This command requires Windows")

It works but feels a bit clunky to me.

image

I'll admit this is a bit of a contrived example. And in case you are wondering, from what I've seen there is no performance advantage between using If/Else or the ternary operatory.

If the goal is succinctness,  PowerShell doesn't care about formatting. These two statements have the same result.

if ($IsLinux) { ls -al } else { Write-Warning "This command requires Linux" }
$isLinux ? (ls -al) : (Write-Warning "This command requires Linux")

Which do you prefer?

What Does This Mean to You?

I'm not expecting Microsoft to backport this operator to previous versions of PowerShell. Which means you have a dependency on PowerShell 7 if you want to use it. For simple conditional statements at the console, I guess I can see the appeal.

image

But if you are writing a script file, I don't see any advantage yet. This is a new feature that many people won't understand at first. Personally, something like this is clearer.

if ((get-date).DayOfWeek -eq "Friday") {
 $var = "tgif"
 } 
 else {
 $var = "blah"         
}

Even if you are new to PowerShell, there's not much mystery about what is happening.

All of this doesn't mean I'm telling you to avoid using this operator. I don't come from a developer background so this operator is not something that I've missed and the traditional If statement works fine for me.

Because I don't have a developer background, if there are compelling use cases for this operator, I'd love to hear about them because I'm betting it will involve something new that I haven't learned yet. For the rest of you with PowerShell 7 preview 4 or later installed, try out the new operator and see where it makes sense for you.

Update

Apparently, Adam Bertram and I are on the same page these days. Here's his take published today at Petri.com https://www.petri.com/using-the-ternary-conditional-operator-in-powershell-7


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

4 thoughts on “Understanding the PowerShell 7 Ternary Operator”

  1. Xavier Plantefève says:
    October 12, 2019 at 4:36 pm

    I don’t remember where I picked the ternary operator, but where I missed it was in assignments. Without it, and to avoid a lengthy if/else, I frequently resorted to:

    $result = (‘not ok’,’ok’)[$isWindows]

  2. Trey Mackalue says:
    October 13, 2019 at 5:54 pm

    > When using an If statement, the Else clause is completely optional. When using the ternary operator the conditional Else component is required.

    Yes, because the ternary operator is an expression, which should yield a result. It’s not useful for side effects, but is very useful in determining the value of a variable to be used later based on some condition.

  3. Scott Ellis says:
    October 18, 2019 at 9:21 am

    Hi Jeff,

    I’m speaking at a conference next week and wanted to mention your memory check powershell. Would you mind if I posted it to a public github, giving you credit? I can take it down after four weeks, but I want people to be able to download it and use it easily, and in its present online form it’s not that easy to piece together. Please email me directly about this or respond to this comment 🙂

    Thanks!

    1. Jeff Hicks says:
      October 21, 2019 at 4:35 am

      I’m not sure which memory check code you are referring to but sure.

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d