- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How Ternary operator in PowerShell Works?
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.
- Related Articles
- Ternary Operator in Java
- Ternary Operator in C#
- Ternary Operator in Python?
- How scriptblock works in PowerShell?
- Changing ternary operator into non-ternary - JavaScript?
- How to overload python ternary operator?
- Conditional ternary operator ( ?: ) in C++
- Ternary Operator in Dart Programming
- How to implement ternary conditional operator in MySQL?
- Java Ternary Operator Examples
- C/C++ Ternary Operator
- Java Ternary Operator Puzzle
- What is a Ternary operator/conditional operator in C#?
- What is ternary operator in C#?
- How out-gridview selection works in PowerShell?
