PowerShell ElseIf Chains
An elseif chain is a list of tests checked in order until one is true. It picks one branch from several choices.
One test after another
A variable is a named box that holds a value. Here $score holds 85.
$score = 85
if ($score -ge 90) { "A" } elseif ($score -ge 75) { "B" } else { "C" }The first true test wins
A score of 95 passes both tests below, but only the first true branch runs.
$score = 95
if ($score -ge 90) { "A" } elseif ($score -ge 75) { "B" } else { "C" }Else catches the rest
When no test is true, the else branch runs.
$score = 40
if ($score -ge 90) { "A" } elseif ($score -ge 75) { "B" } else { "C" }Example
$score = 72
$grade = ""
if ($score -ge 90) { $grade = "A" } elseif ($score -ge 80) { $grade = "B" } elseif ($score -ge 70) { $grade = "C" } else { $grade = "D" }
"Score $score earns grade $grade"Key points
- Elseif: a test that runs only when the earlier if test is false.
- Order: PowerShell checks the tests from top to bottom and stops at the first true test.
- Else: a final branch that runs when every test is false.
- Use elseif chains to sort one value into exactly one group.
- Comparison: each test uses a comparison operator such as -ge or -eq.
In this example, $score holds 72 and $grade starts empty. The chain checks 90, then 80, then 70. The 70 test is the first true test, so $grade becomes C. The last line prints the score and its grade.
Note
PowerShell spells it elseif as one word, not else if.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
$score is 82. What does this chain print? if ($score -ge 90) { "A" } elseif ($score -ge 80) { "B" } else { "C" }