0
0
PowerShellscripting~5 mins

Ternary operator (PowerShell 7+)

Choose your learning style9 modes available
Introduction
The ternary operator lets you choose between two values quickly based on a condition, making your code shorter and easier to read.
You want to set a variable to one value if a condition is true, and another if false.
You need a quick decision inside a script without writing full if-else blocks.
You want to simplify simple conditional assignments in your automation scripts.
Syntax
PowerShell
condition ? value_if_true : value_if_false
The condition is checked first; if true, the first value is used, else the second.
This operator is available in PowerShell 7 and later versions.
Examples
Sets $status to 'Adult' if $age is 18 or more, otherwise 'Minor'.
PowerShell
$age = 20
$status = $age -ge 18 ? 'Adult' : 'Minor'
$status
Checks if $number is even or odd and stores the result.
PowerShell
$number = 5
$result = ($number % 2) -eq 0 ? 'Even' : 'Odd'
$result
Chooses an activity based on whether it is sunny.
PowerShell
$isSunny = $true
$activity = $isSunny ? 'Go outside' : 'Stay inside'
$activity
Sample Program
This script checks if the score is 60 or more. If yes, it sets grade to 'Pass', else 'Fail'. Then it prints both values.
PowerShell
$score = 75
$grade = $score -ge 60 ? 'Pass' : 'Fail'
Write-Output "Score: $score"
Write-Output "Result: $grade"
OutputSuccess
Important Notes
The ternary operator is a shortcut for simple if-else assignments.
Use parentheses to clarify complex conditions if needed.
Avoid using ternary for very long or nested conditions to keep code readable.
Summary
The ternary operator helps make quick decisions in one line.
It works like a mini if-else: condition ? true-value : false-value.
Available in PowerShell 7+, it simplifies your scripts and saves space.