This post will illustrate PowerShell’s ternary operator.
What is Ternary Operator in PowerShell?
A ternary operator “?” takes two expressions that need to be compared based on the condition. After that, there comes a ternary operator “?” and an output section. The output section is separated by the colon (:). The statement at the left of the colon gets executed upon the condition being true. When the condition is false, then the right-side statement comes into execution.
Syntax
In the above syntax, the left of the ternary operator refers to a condition, and the right side contains the output.
Example 1: Use Ternary Operator in PowerShell to Compare Values
This example will illustrate the working of the ternary operator in PowerShell:
In this code example:
- First, we have created a condition inside the small braces.
- After that, we added the ternary operator “?” with two outputs, separated by a colon.
- Upon the true condition, the output on the left side will be invoked. Else, the right-side statement will print out on the console:
As condition 12 is less than 14 has been evaluated as true, the output has been displayed as “True”.
Now, check what happens if the added condition turns out to be false:
Output
Example 2: Use Ternary Operator in PowerShell to Compare Variable Values
In this example, we will first store the values into the variables and, after that, apply the ternary operator:
> $b = 3
> ($a -gt $b) ? "True" : "False"
In this code example:
- First, we created two variables having the given integer values.
- After that, we compared them via the ternary operator “?”.
The above output signifies that the value of the former variable is less than the latter one. So, “False” has been displayed on the console.
Now, let’s change the condition and make it true:
> $b = 3
> ($a -gt $b) ? "True" : "False"
The condition proved to be true, which is why the resultant output is “True”.
Conclusion
The ternary operator “?” was introduced in PowerShell 7.2 as the keyword “?” (question mark). This operator is the simplified form of the “if-else” condition. In its first part, it defines the condition, and in the later part, it gives an output. A colon separates the output. If the condition is true, then the left side of the colon will get executed. Otherwise, the right side will get executed. This write-up guided about the ternary operator in PowerShell.