Ternary Operator in PowerShell

Rohan Timalsina Apr 03, 2022 Jan 11, 2022
Ternary Operator in PowerShell

The ternary operator was introduced in PowerShell version 7.0. So, you will need the PowerShell with version 7.0 or later to use the ternary operator.

The ternary operator can shorten the if else statement because the ternary operator contains a single line of code. This tutorial will introduce the ternary operator in PowerShell.

Use the Ternary Operator in PowerShell

The ternary operator includes the question mark (?) symbol. The general syntax is as follows:

(Condition) ? "Output if True" : "Output if False"

As you can see, the ternary operator takes three operands: a condition and two expressions to print based on the condition.

The left side contains the condition, and the right side includes the output to display depending on the condition. The output is displayed in the form of Boolean. The first part will be displayed if the condition is true, and the second part will be displayed if the condition is false.

Let’s see how the ternary operator works in the PowerShell.

Here, the condition says 5 is greater than 10.

(5 -gt 10) ? "Yes" : "No"

As we can see, it prints the second part No because the condition is false.



In the below example, the first part is printed because the condition is true.

$a = 4; $b= 4
($a -eq $b) ? "$a is equal to $b" : "$a is less than $b"


4 is equal to 4

You can have any condition and print the Boolean output based on the condition. It is similar to the if...else statement.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Operator