PowerShell If Else
An if statement runs one block of code only when its test is true. An else block runs instead when the test is false.
Choose between two words
Test whether an age reaches eighteen. The true branch prints one word, and the else branch prints the other.
$age = 20
if ($age -ge 18) { "adult" } else { "minor" }See the else branch run
Change the age so the test is false. Now the else branch runs instead of the if branch.
$age = 15
if ($age -ge 18) { "adult" } else { "minor" }Combine two tests in one if
Two tests can join with -and. Both must be true for the if branch to run.
$age = 20
$hasTicket = $true
if (($age -ge 18) -and $hasTicket) { "welcome" } else { "not yet" }Example
$score = 72
$passMark = 60
if ($score -ge $passMark) { "passed" } else { "failed" }Key points
- Test: The test sits in parentheses after if, and it uses a comparison like -gt.
- True branch: The code in the if braces runs only when the test is true.
- Else branch: The code in the else braces runs only when the test is false.
- One branch: Only one of the two branches ever runs for a single test.
- Branch work: Each branch can print a value or store a value in a variable.
In this example, a score and a pass mark are stored first. The if test compares them, and because the score reaches the pass mark, the if branch prints passed.
Note
The else block needs no test of its own. It catches every case the if test rejects.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does this print when $age is 16? if ($age -ge 18) { "adult" } else { "minor" }