Using the Ternary Conditional Operator in PowerShell 7

PowerShell 7.0 Beta 4 introduces a familiar mainstay of most programming languages, the Ternary Operator. Using a much shorter syntax for if/then logic, it makes defining conditional values for properties much more concise and easy to read. This certainly isn’t the only use case, it is merely one that I encounter often and one where the Ternary Operator works wonders to simplify.

Additionally, if you are a heavy user of the command line, the shorter syntax will help you quickly test code and prototype functionality. Another great example is using the Ternary Operator within string concatenation or using the format operator. The shorter syntax means that, for generally simple conditions, you can combine multiple lines of code into one and increase the general readability by a large margin.

Using If/Then Logic

Say you want to make a comparison that will then determine a specific action to take. An if statement, with a potential else statement, is the usual way to approach this use case. As in most languages, you take one value and using a comparison operator compare it to another value to output a boolean value, which simplify means true or false. As seen below, a simple if/then statement compares the values of $a and $b and finding them unequal outputs $false in this case.

Sponsored Content

Passwords Haven’t Disappeared Yet

123456. Qwerty. Iloveyou. No, these are not exercises for people who are brand new to typing. Shockingly, they are among the most common passwords that end users choose in 2021. Research has found that the average business user must manually type out, or copy/paste, the credentials to 154 websites per month. We repeatedly got one question that surprised us: “Why would I ever trust a third party with control of my network?

$a = 1
$b = 2

if ($a -eq $b) {
} else {

# Output is: $false

Although the comparison, in this case, is simple. You can certainly get more complex, comparing multiple conditions and having multiple if/else clauses. Doing so can evaluate complex conditions depending on what you need to do. Below is an example of multiple conditions and if/else statements.

if (
    ($user -eq 'Joe' -and $inactive -eq $true) -or
    ($user -eq 'Sally' -and $inactive -eq $true)
) {
    $user | Set-UserState -Inactive $false
} elseif ($user -eq 'Mary' -and ($inactive -eq $true -or $expires -eq $true)) {
    $user | Set-UserState -Inactive $false
    $user | Set-UserState -Expires $false
} else {
    "No users are inactive"

Introducing the Ternary Operator

You might ask yourself why not just use the regular old if/then statement, it seems concise and easy enough to use. Well, if/then works great for many things, but when you need to define the values of a large number of properties, it would be a lot nicer to have a more concise inline syntax that can directly assign the values to properties as necessary. In all its glory here is the new Ternary Operator, refactoring our above example:

($a -eq $b) ? $true : $false

Although it’s simple, let’s look at an example where we can see how it really shines. When defining custom objects, for example, suppose you want to assign property values conditionally. You could define a whole lot of lengthy if statements or you could inline assign them via the new Ternary Operator.

The old way, using lots of if/then statements to define the property values.

if ($a -eq $b) {
    $property1 = $true
} else {
    $property1 = $false

if ($test) {
    $property2 = "Here"
} else {
    $property2 = "There"

if (Test-Path $Path) {
    $property3 = $true
} else {
    $property3 = $false

    "Property1" = $property1
    "Property2" = $property2
    "Property3" = $property3

Here is the refactored version using the new PowerShell 7.0 Ternary Operator syntax. You can see there’s a lot less typing!

    "Property1" = (($a -eq $b) ? $true : $false)
    "Property2" = (($test) ? "Here" : "There")
    "Property3" = ((Test-Path $Path) ? $true : $false)

What are some other real-world examples? Here are just a sampling of some common conditions that come up in daily use.

  • $IsCoreCLR ? 'pwsh' : 'powershell'
  • (Test-Path $path) ? "Path exists" : "Path not found"
  • $env:CI -eq 'true' ? '-Tag CI' : '-Tag Daily'

When Doesn’t The Ternary Operator Work?

I showed an example earlier, explaining a more complex example using multiple conditions and if/else statements. As you may have guessed, the Ternary Operator is generally meant for pretty simple situations. It may not be suited for a much more complex set of conditions that require multiple lines of code to be executed. You might be able to shoehorn some of it, but it will probably end up not being all that readable.

As with all language features, they each have their best use cases and the Ternary Operator is no different in this case. There is a reason it’s sometimes referred to as an inline if statement, simple concise logic tests are ideal. Anything larger than that will probably benefit from using the traditional if/then statement.

Can’t Use PowerShell 7.0?

Perhaps you aren’t ready to make the jump into PowerShell 7.0 or your organization can’t upgrade quite yet. There have been a few takes on alternative syntaxes, but one of my favorites is the following syntax as outlined here. You can see how to use it below.

# Condition to test
$CarColor = 'Blue'

# Hashtable with $true & $false as the keys, and the subsequent results as the values
@{ $true = 'The car color is blue'; $false = 'The car color is not blue'

# Lookup that tests the condition, outputting the relevant value
[$CarColor -eq 'Blue']

Even if you can’t upgrade to PowerShell 7.0 yet, this method should hopefully illustrate just how handy it can be to have that more concise syntax.

Use the Ternary Operator Today

As of this writing, you can install PowerShell 7.0, in its beta form, with the general availability coming out shortly. Now that you have seen how to easily refactor your code using the shorter syntax, hopefully, you find lots of cases that it will not only simplify your code but make developing new functionality that much faster!

Related Topics:


Don't have a login but want to join the conversation? Sign up for a Petri Account

Comments (3)

3 responses to “Using the Ternary Conditional Operator in PowerShell 7”

  1. <p>You don't even need a cumbersome hashtable for a ternary alternative. Given that powershell casts booleans as 0 and 1 when an integer is expected, and that arrays are ordered, just go with:</p><p><br></p><p>('The car color is not blue','The car color is blue')<span style="color: rgb(0, 0, 255);">[</span><span style="color: teal;">$CarColor</span><span style="color: rgb(0, 111, 224);"> </span><span style="color: rgb(206, 0, 0);">-eq</span><span style="color: rgb(0, 111, 224);"> </span>'Blue'<span style="color: rgb(0, 0, 255);">]</span></p><p>&nbsp;</p><p><br></p>

  2. <p>You can simplify the PSCustomObject code by getting rid of some unnecessary parens:</p><p><br></p><p>[PSCustomObject]@{</p><p>&nbsp;&nbsp;"Property1" = $a -eq $b ? $true : $false</p><p>&nbsp;&nbsp;"Property2" = $test ? "Here" : "There"</p><p>&nbsp;&nbsp;"Property3" = (Test-Path $Path -ea 0) ? $true : $false</p><p>}</p><p><br></p><p>Otherwise, good stuff. Thanks!</p>

  3. <p>I really don't see the big deal.</p><p>This works perfect i powershell 5:</p><p><br></p><p>[PSCustomObject]@{</p><p>&nbsp;&nbsp;"Property1" = $a -eq $b</p><p>&nbsp;&nbsp;"Property2" = if ($test) { "Here" } else { "There" }</p><p>&nbsp;&nbsp;"Property3" = if (Test-Path $Path) { $true } else { $false }</p><p>}</p>

Leave a Reply

Entrepreneur, hustler, husband, dad, Automator, content producer, published author, Microsoft MVP, DevOps pro and passionate problem-solver.
13 Email Threat Types to Know About Right Now

As email threats evolve and multiply, keeping track of them all—and staying protected against the many different types—becomes a complex challenge. Today, that requires more than just the traditional email gateway solution that used to be good enough.

In this eBook you will learn:

  • What are the most common and challenging email attacks for organizations?
  • How to defend against sophisticated email threats, such as spoofing, social engineering, and fraud
  • How to protect employees at the inbox level with the right technologies and security-awareness training
  • How to use a multilayered protection strategy to reduce susceptibility to email attacks and better defend your business and employees

Sponsored by: