🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Ternary Operator

The ternary operator is a short if-else written on one line. It picks one of two values based on a test.

Pick the true value

The age is 20, so the test is true and the first value is picked.

$age = 20
$age -ge 18 ? "adult" : "minor"

Pick the false value

The age is 15, so the test is false and the second value is picked.

$age = 15
$age -ge 18 ? "adult" : "minor"

Store the result

The chosen value can be stored in a variable for later use.

$score = 88
$result = $score -ge 60 ? "pass" : "fail"
$result

Example

$temp = 28
$label = $temp -gt 25 ? "warm" : "cool"
"A $temp degree day is $label"

Key points

  • Ternary: a short test that picks one of two values.
  • Form: the test comes first, then a question mark, then the true value, then the false value.
  • Use the ternary operator to assign one of two values in a single line.
  • Test: the test uses a comparison operator such as -gt.
  • Result: only the chosen value is used, and the other value is ignored.

In this example, $temp holds 28. The test asks whether 28 is greater than 25, which is true, so $label becomes warm. The last line prints the temperature and its label.

Note

PowerShell 7 added the ternary operator, so older PowerShell versions do not have it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does this line print? $x = 4; $x -gt 5 ? "big" : "small"