Core Skills Level: Intermediate Chapter 9: Make Scripts Decide and Repeat
Sequence and selection: if, elseif, else
Sequence is the default: run one step, then the next. Selection adds a choice: run a block only when a condition is true, or choose between branches.
Lesson 1 of 2 in Chapter 9: Make Scripts Decide and Repeat. Previous step in this path: Advanced Functions. 3 learning objectives, 6 examples, and a knowledge check.
Start: what you will learn
Sequence is the default: run one step, then the next. Selection adds a choice: run a block only when a condition is true, or choose between branches.
Learning objectives
- Explain sequence in one sentence
- Write an if statement with a correct condition
- Add elseif and else branches in the right order
Concept in simple words
What it is: sequence means code runs one step after another, in order, from top to bottom. Selection means code chooses a branch. With if, elseif, and else, PowerShell tests conditions in order and runs only the block for the first condition that is true. If no condition is true and an else block is present, the else block runs. If no condition is true and there is no else block, nothing in that chain runs, and the script simply moves on to the next line after the chain.
Why it works
Why it exists: without selection, a script would do the same thing every time, no matter what it found. That is not useful for real work. A service can be running or stopped. A disk can have plenty of space or almost none. A score can fall in one band or another. Selection lets one script react correctly to each case, instead of forcing you to write a separate script for every possible value. Sequence gives you order, and selection gives you judgement.
What PowerShell is doing behind the command: PowerShell reads the if line, evaluates the expression inside the parentheses, and turns the result into a true or false answer. If the answer is true, it runs the block inside the braces that follow, then it leaves the whole if chain. It does not go back and test the later branches. If the answer is false, it moves to the next elseif line and tests again, in the same way. Only after every if and elseif test has failed does it run else, and else has no test of its own. Think of else as the words for everything else, not as another test.
The anatomy of the statement: every branch has three parts, and mixing them up is a common beginner error. First comes the keyword: if, elseif, or else. Second, for if and elseif only, comes a condition in parentheses, such as ($status -eq "Running"). Third comes a block in braces, such as { Write-Output "Service is running" }. The braces are required in PowerShell, even for a block with only one line. The condition is the question, and the block is what happens when the answer is yes. Else has no parentheses and no condition, because it is the answer for every case that is left.
Comparison operators, in plain words: a condition usually compares two values. The operator -eq means equal, -ne means not equal, -gt means greater than, -ge means greater than or equal to, -lt means less than, and -le means less than or equal to. So $score -ge 90 asks whether the score is 90 or more, and it is true for 90 and for 95, but false for 89. The single equals sign, =, is completely different. It assigns a value, as in $status = "Running". It does not ask a question. That is why you must never write if ($status = "Running"), because that stores a value instead of testing one, and the result will usually look true even when it is not the test you meant.
Truthiness, or what counts as true when there is no comparison: sometimes an if test is not a comparison at all. It can be a single value, such as if ($isReady) or if ($name). PowerShell converts that value to true or false using simple rules. The value $true is true, and $false is false. The number 0 is false, and any other number is true. An empty string, written as "", is false, and any string with characters in it is true. The value $null, which means no value, is false. Watch out for one trap: the text "False", with quotes, is a non empty string, so it counts as true. It is only the value $false, without quotes, that counts as false. When you are unsure, write an explicit comparison, such as if ($name -ne ""), instead of relying on truthiness alone.
Logical operators, or how to combine questions: use -and when every part must be true, use -or when at least one part must be true, and use -not to flip an answer. For example, ($age -ge 18) -and ($hasTicket -eq $true) is true only when both parts are true. Change -and to -or, and the same test becomes true when either part is true, which is a much weaker rule. Use parentheses around each part, as in the example, so the reader can see exactly how the parts group together. Do not rely on memory for grouping when a test has both -and and -or in it. Parentheses make your intent visible, and they prevent a small grouping surprise from changing the whole decision.
Case sensitivity, a small rule with big effects: by default, string comparisons in PowerShell ignore case. That means "Running" -eq "running" is true, and "Ana" -eq "ana" is true. If you need an exact case match, use the case sensitive form -ceq instead of -eq, as in "Running" -ceq "running", which is false. If you want to make the usual behaviour explicit, you can use -ieq, where the letter i stands for insensitive. For most beginner scripts, the default is what you want, but you must know it exists, or a name that differs only by capital letters will surprise you by matching.
Think of it like this
Think of it like this: a fork in a road with signposts, read from top to bottom. You take the first road whose sign matches where you want to go, and you ignore the rest, even if a later sign would also have matched. If the signs are in the wrong order, a general sign can send you down the wrong road before you ever reach the specific one. A score example makes this concrete. If you test score 75 or more before you test score 90 or more, then a score of 95 will match the first, general test and print the wrong grade, and the specific test for 90 will never get a chance.
How it works, step by step
How it works, step by step: First, write the steps in the order they must happen, so every value is set before it is used. A script that reads a variable before it sets that variable will not work, even if every line on its own looks right. Second, decide what question each branch must answer, and write it with a comparison operator, not with a single equals sign. Third, order the branches from most specific to most general, so a narrow case is caught before a wide case swallows it. Fourth, finish with else for everything left, and only if you truly have a sensible action for everything left. Fifth, read the chain out loud with a test value, and check that exactly one branch can run for that value.
Boundary thinking, the skill that separates a working chain from a nearly working chain: always test the edge values, not only the easy middle values. For a band that starts at 90, test 89, 90, and 91. For a disk warning that starts below 10, test 9, 10, and 11. Ask yourself whether the boundary itself belongs in the higher band or the lower band, then pick -ge or -gt, -le or -lt, to match that answer. An off by one error is the most common selection bug, and it hides well, because the chain still runs and still prints something. It just prints the wrong branch for the boundary value, and only a boundary test will catch it.
Let us walk through the first example, the service test, line by line. The first line, $status = "Running", stores the text Running in the variable $status. Note the single equals sign here, because this line is storing, not testing. The second line, if ($status -eq "Running"), asks whether the stored value equals Running. Because string comparison ignores case by default, even "running" in lower case would match here. The answer is true, so the block runs and prints Service is running. The else block is skipped completely. In the output, look for exactly one line. If you change $status to "Stopped", the if test becomes false, the if block is skipped, and the else block runs instead, printing Service is not running. If you change the test to -ne, meaning not equal, the branches flip: Running would now take the else path, which shows why the operator, not just the value, decides the result.
Let us walk through the second example, the score bands, with the value 75. The first line stores 75 in $score. The first test, $score -ge 90, asks whether 75 is 90 or more. It is false, so the first block is skipped. The second test, elseif ($score -ge 75), asks whether 75 is 75 or more. It is true, because -ge includes the boundary itself, so the block runs and prints B. The else block never runs, because a branch already matched. Now change one part at a time and predict the result before you read it. Change $score to 90, and the first branch matches, printing A. Change $score to 74, and both tests fail, so else prints C. Change the second test from -ge 75 to -gt 75, and a score of exactly 75 would fall through to else and print C, which is the off by one error in action.
Let us walk through the third example, the disk space check, with the value 15. The first line stores 15 in $diskFree. The if test, $diskFree -lt 10, asks whether 15 is less than 10. It is false, so the first block is skipped. The elseif test, $diskFree -lt 20, asks whether 15 is less than 20. It is true, so that block runs and prints Disk space getting low. The else block, which would print Plenty of disk space, does not run, because a branch already matched. Change $diskFree to 9, and the first branch matches, printing Low disk space. Change it to 20, and the elseif test fails, because 20 is not less than 20, so else prints Plenty of disk space. That boundary case is worth testing every time, because it is where -lt and -le give different answers.
Let us walk through the fourth example, the combined test, line by line. The first two lines store an age of 20 and a ticket flag of $true. The if line tests ($age -ge 18) -and ($hasTicket -eq $true). The first part is true, because 20 is 18 or more. The second part is true, because the flag equals $true. With -and, both parts must be true, so the whole test is true, and the block prints Entry allowed. Now change one part: set $hasTicket to $false, and the second part becomes false, so the whole -and test becomes false, and else prints Entry not allowed, even though the age part is still true. Change -and to -or with the same values, and the test becomes true when either part is true, so a visitor with no ticket would wrongly get in. That single word changes the rule, so read logical operators as carefully as you read comparison operators.
Let us walk through the fifth example, the nested if, which is an if inside another if. The outer test asks whether the user is logged in. If that is false, the outer else block runs and prints Please log in, and the inner test is never even reached. If the outer test is true, PowerShell enters the outer block and meets the inner test, which asks whether the user is an admin. If that is true, it prints Welcome, admin. If it is false, the inner else prints Welcome, user. The key point is that else always belongs to the nearest if above it that does not already have an else, so indentation is not just decoration. Indent the inner block further than the outer block, so a reader can see at a glance which else belongs to which if. Keep nesting shallow, one or two levels, because deeper nesting quickly becomes hard to trace.
Let us walk through the sixth example, the switch alternative, and when to prefer it. Switch tests one value against a list of cases, instead of repeating the same variable in a long if chain. Here the value is $status. The first case, "Running", matches, so its block prints Service is running, and break leaves the switch at once. Without break, PowerShell would keep checking later cases, and a value that matched more than one case could run more than one block, which is rarely what you want. If no case matches, the default block runs, just like else. Change $status to "Paused", and no case matches, so default prints Unknown status. Use switch when you are comparing one value against many fixed values, and keep if chains for tests that compare different variables or use ranges, such as score bands, where switch is less natural.
When to use it
When to use it, and when not to: use if when a script must react to different values, such as a service that is running or stopped, or a score that falls in a band. Use elseif for a short list of ordered bands or stages, and use else as a safe fallback that also tells you when an unexpected value arrived. Do not use a long if chain when switch would say the same thing more clearly for one value against many fixed labels. Do not put a general test above a specific test, because the general test will swallow the specific case. Do not write a chain with many overlapping tests and no else, and then wonder why some inputs print nothing. Silence is also an answer, and it usually means no branch matched.
How to trace a chain when the result surprises you: work backwards from the output, in three questions. First, what was the value of each variable just before the if line, and was it set before it was read. Second, which test was the first one to be true, and did an earlier, wider test steal the value first. Third, what would the boundary values do, and did you test them. Write the answers down for one failing input, change one thing, and test again. Guessing at two changes at once makes it impossible to know which change fixed the problem, or whether either change did.
Edge cases to keep in mind: a missing else means an unmatched input produces no output at all, which can look like the script did nothing, when in fact it ran correctly and simply matched nothing. A variable that was never set counts as $null, which is false in a truthiness test, but comparing it with -eq can behave in ways that surprise beginners, so set every variable before you test it. A number stored as text, such as "15" with quotes, is not the same kind of value as the number 15, so compare numbers with numbers and text with text, and quote text values in your tests. Finally, remember that these examples only read values and print messages. They change nothing on a machine, which makes them safe to practise with, but a branch in a real script can run a command that changes something, so test a new chain with safe values first, before you let it run a changing command.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
if (<condition>) { <block> } elseif (<condition>) { <block> } else { <block> }Example 1
Tests one condition, runs one branch. Only the matching branch runs. The first line stores, using =, and the if line tests, using -eq. Change "Running" to "Stopped" and the else branch runs instead.
$status = "Running"
if ($status -eq "Running") {
Write-Output "Service is running"
} else {
Write-Output "Service is not running"
}Illustrative output: Service is running
Example 2
Tests in order, most specific first. A score of 75 matches the second branch, not the third, because -ge includes 75 itself. A score of 90 would match the first branch, and a score of 74 would fall through to else.
$score = 75
if ($score -ge 90) {
"A"
} elseif ($score -ge 75) {
"B"
} else {
"C"
}Illustrative output: B
Example 3
The first line stores the number 15 in $diskFree. The if test uses -lt, which means less than, so 15 is not less than 10 and the first branch is skipped. The elseif test checks less than 20, which is true for 15, so that branch runs. The else branch is only a fallback, and it does not run here, because a branch already matched.
$diskFree = 15
if ($diskFree -lt 10) {
Write-Output "Low disk space"
} elseif ($diskFree -lt 20) {
Write-Output "Disk space getting low"
} else {
Write-Output "Plenty of disk space"
}Illustrative output: Disk space getting low
Example 4
Combines two tests with -and, so both parts must be true. The age part is true and the ticket part is true, so the if block runs. Set $hasTicket to $false and else runs, even though the age part is still true.
$age = 20
$hasTicket = $true
if (($age -ge 18) -and ($hasTicket -eq $true)) {
Write-Output "Entry allowed"
} else {
Write-Output "Entry not allowed"
}Illustrative output: Entry allowed
Example 5
A nested if: the inner test is only reached when the outer test is true. Here the user is logged in but is not an admin, so the inner else runs. The outer else would run only when $isLoggedIn is $false.
$isLoggedIn = $true
$isAdmin = $false
if ($isLoggedIn) {
if ($isAdmin) {
Write-Output "Welcome, admin"
} else {
Write-Output "Welcome, user"
}
} else {
Write-Output "Please log in"
}Illustrative output: Welcome, user
Example 6
A switch alternative for one value against fixed labels. The value matches "Running", so that block runs and break leaves the switch. Change $status to "Paused" and no case matches, so default runs. Keep break in each case, or later cases can still be checked.
$status = "Running"
switch ($status) {
"Running" { Write-Output "Service is running"; break }
"Stopped" { Write-Output "Service is stopped"; break }
default { Write-Output "Unknown status" }
}Illustrative output: Service is running
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Using = instead of -eq in a condition, which assigns instead of comparing, and always looks true.
- Putting a general elseif above a specific one, so the specific branch never runs. Order matters.
- Putting else before elseif, or putting else in the middle of a chain, so the later branches can never run and PowerShell reports a syntax problem or silently skips them.
- Using -gt when you meant -ge, or -lt when you meant -le, so a boundary value such as exactly 90 or exactly 20 falls into the wrong branch. Test the boundary itself.
- Leaving out else and then thinking the script failed, when in fact no branch matched and the chain correctly printed nothing. Add else, or check for the silent case, when silence would confuse you.
- Letting else attach to the wrong if in a nested chain. Else belongs to the nearest if without an else, so poor indentation can make you read the pairing wrong. Indent each level clearly.
- Forgetting that string comparison ignores case by default, so "Running" matches "running", or forgetting the quotes around text, so PowerShell treats a word as a variable or command name instead of text.
- Combining -and and -or without parentheses, so the grouping is not what you meant and a value passes a test it should have failed. Put each part in parentheses and read the combined rule out loud.
Knowledge check
Knowledge check
In an if, elseif, else chain, how many branches run?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: order is everything in sequence, and order is everything in selection too. Set before you read, test from specific to general, put else last as the fallback for everything left, and remember that only the first true branch runs. Test the boundaries, read the operator as carefully as the value, and use parentheses to make combined tests clear. If you can trace a chain with a pencil and say why it took the path it took, you understand selection, and longer scripts will stop looking scary.
Next step: Iteration: for, while, and foreach