PowerShell 7.0 Beta 4 introduces a familiar mainstay of most programming languages, the Ternary PowerShell 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 of the PowerShell Ternary Operator 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.
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 use a comparison operator to compare it to another value to output a boolean value, which simply 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.
$a = 1
$b = 2
if ($a -eq $b) {
$true
} else {
$false
}
# 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"
}
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
}
[PSCustomObject]@{
"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!
[PSCustomObject]@{
"Property1" = (($a -eq $b) ? $true : $false)
"Property2" = (($test) ? "Here" : "There")
"Property3" = ((Test-Path $Path) ? $true : $false)
}
What are some other real-world examples? Here is 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'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.
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:
# 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.
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 PowerShell Ternary Operator syntax, hopefully, you find lots of cases that it will not only simplify your code but make developing new functionality that much faster!
While the native PowerShell ternary operator is only available in PowerShell 7.0 and later, you can use alternative approaches when working with Azure Functions, such as creating a custom function that mimics ternary behavior or using Switch statements for conditional operations.
The PowerShell ternary operator generally performs slightly faster than traditional if-else statements because it’s evaluated as a single expression, making it particularly efficient for simple conditional operations in scripts and functions.
Yes, you can nest PowerShell ternary operators, but it’s recommended to limit nesting to maintain code readability. Using parentheses helps clarify the order of operations when nesting multiple ternary expressions.
The PowerShell ternary operator works seamlessly with array operations and can be used within pipeline commands, allowing for compact conditional logic when filtering, transforming, or processing collections of data.
Yes, the PowerShell ternary operator can be combined with type casting and null-coalescing operations, making it versatile for handling type conversions and null checks in a concise manner.