How Ternary operator in PowerShell Works?

PowerShellMicrosoft TechnologiesSoftware & Coding

The ternary operator in PowerShell was introduced with the PowerShell version7.0. The ternary operator has ‘?’ (question mark) symbol and its syntax is,

[Condition] ? (output if True) : (output if false)

The left side of the ternary operator is condition and the right side is output based on the condition statement. The output from the condition is in the forms of the Boolean, if the condition is true, the True block will be executed and if the condition is false, the False block will be executed. For example,

Example

$a = 5; $b = 6
($a -gt $b) ? "True" : "false"

Output

false

As you can see the value 5 is less than 6 so the above condition is false and the second block is executed. You can also modify the statement like,

($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")

Output

5 is less than 6

You can see that the amount of code is reduced by just one line and if we have written the same with if/else condition then,

$a = 5; $b = 6

if($a -gt $b){"$a is greater than $b"}
else{"$b is greater than $a"}

So the use of the ternary operator seems simple. You can also use cmdlet on the left side of the operator which returns the Boolean value.

Example

(Test-Connection google.com -Count 2 -Quiet) ? "Google.Com server is reachable" : "Google.Com server is unrechable"

Output

Google.Com server is reachable

Try to make this ternary operator as simple as possible. It won’t work always if the right side part of the ternary operator is used for scripting purposes.

raja
Published on 11-Nov-2020 12:36:21
Advertisements