0
0
PowerShellscripting~5 mins

Ternary operator (PowerShell 7+) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in PowerShell 7+?
The ternary operator is a compact way to write an if-else statement in one line. It uses the syntax: condition ? valueIfTrue : valueIfFalse.
Click to reveal answer
beginner
How do you write a ternary operator to check if a number is even or odd in PowerShell?
You can write: $result = ($number % 2 -eq 0) ? 'Even' : 'Odd'. This sets $result to 'Even' if the number is divisible by 2, otherwise 'Odd'.
Click to reveal answer
intermediate
True or False: The ternary operator in PowerShell 7+ can only be used with simple expressions.
False. The ternary operator can be used with any expressions, including complex ones, as long as they return a value.
Click to reveal answer
beginner
What will this PowerShell code output? <br>$age = 20; $status = ($age -ge 18) ? 'Adult' : 'Minor'; $status
It will output Adult because the condition $age -ge 18 (age greater or equal to 18) is true.
Click to reveal answer
beginner
Why use the ternary operator instead of a full if-else statement?
The ternary operator makes code shorter and easier to read when you have simple conditions that assign values based on true or false.
Click to reveal answer
What is the correct syntax of the ternary operator in PowerShell 7+?
Acondition : valueIfTrue ? valueIfFalse
Bif (condition) {valueIfTrue} else {valueIfFalse}
Ccondition ? valueIfTrue : valueIfFalse
Dcondition ? valueIfFalse : valueIfTrue
What will this output? <br>$x = 5; $y = ($x -gt 10) ? 'Big' : 'Small'; $y
ABig
B5
CError
DSmall
Can the ternary operator be nested in PowerShell 7+?
AYes, you can nest ternary operators.
BNo, nesting is not allowed.
COnly with special syntax.
DOnly in PowerShell 5.1.
Which PowerShell version introduced the ternary operator?
APowerShell 5.1
BPowerShell 7
CPowerShell 6
DPowerShell 4
What does this code do? <br>$result = ($true) ? 'Yes' : 'No'
ASets $result to 'Yes'
BSets $result to 'No'
CThrows an error
DSets $result to $true
Explain how the ternary operator works in PowerShell 7+ and give a simple example.
Think of it as a short if-else that picks one of two values.
You got /3 concepts.
    Describe a situation where using the ternary operator makes your PowerShell script easier to read.
    When you want to choose between two values quickly.
    You got /4 concepts.