Conditions and loops
Make decisions with if and switch, and repeat work with foreach, for, while and do loops.
- Branch with if/elseif/else and predict what counts as true
- Match values with switch, including wildcards, regexes and arrays
- Loop with foreach, for, while and do, and control them with break and continue
1if ($temperature -gt 900) {
2 'Too hot - even for Ember'
3} elseif ($temperature -gt 400) {
4 'Perfect for firedrakes'
5} else {
6 'Light the furnace'
7}The condition doesn’t have to be a comparison - any value works. These count as false: $false, 0, '' (empty string), $null, and an empty array. Almost everything else is true - including the string 'False' and the string '0'.
Try it
Truthy or falsy?
Would if (<value>) { ... } run its block?
“0”
“'0'”
“'False'”
“''”
“$null”
“@()”
“@('Ember')”
“Get-ChildItem *.missing”
switch
switch compares a value with several cases. Unlike many languages, it runs every case that matches (use break to stop after one), and it has useful options:
switch -Wildcarduses-likepatterns;switch -Regexuses regexes (and fills$Matches).- A case can be a script block that tests
$_:{ $_ -gt 10 } { 'big' }. defaultruns when nothing else matched.- Give
switchan array and it processes each element in turn - a loop and a decision in one.
1foreach ($wingspan in 2, 9, 15) {
2 switch ($wingspan) {
3 { $_ -lt 5 } { "$wingspan m: fits in the cottage" }
4 { $_ -ge 5 } { "$wingspan m: needs the big barn" }
5 { $_ -ge 12 } { "$wingspan m: ...and a bigger door" }
6 }
7}
8switch -Wildcard ('Firedrake', 'Stormwing', 'Pebble') {
9 'Fire*' { "$_ breathes fire"; continue }
10 '*wing' { "$_ flies"; continue }
11 default { "$_ is a mystery" }
12}2 m: fits in the cottage 9 m: needs the big barn 15 m: needs the big barn 15 m: ...and a bigger door Firedrake breathes fire Stormwing flies Pebble is a mystery
The second switch walks through an array. continue means “this element is done, move on to the next one”. break would stop the whole switch - including the elements still waiting - so changing the first continue to break would print only the firedrake line. Try it: press Edit and experiment.
Loops
| Loop | Use when |
|---|---|
foreach ($item in $collection) { } | you have a collection - the everyday loop |
for ($i = 0; $i -lt 10; $i++) { } | you need a counter |
while ($condition) { } | you repeat while something is true (maybe zero times) |
do { } while ($condition) / do { } until ($condition) | the body must run at least once |
break leaves a loop, continue jumps to the next round. Don’t confuse the foreach statement with the ForEach-Object cmdlet: the statement loops over a collection that’s already in memory (and is faster); the cmdlet processes pipeline objects one at a time as they arrive.
1for ($day = 1; $day -le 3; $day++) {
2 "Day ${day}: feed the hatchlings"
3}
4$eggs = 5
5while ($eggs -gt 0) {
6 $eggs -= 2
7 "Hatched two, $([math]::Max($eggs, 0)) left"
8}
9foreach ($name in 'Ember', 'Glim', 'Skyla', 'Pebble') {
10 if ($name -eq 'Glim') { continue }
11 if ($name -eq 'Pebble') { break }
12 "Inspecting $name"
13}Day 1: feed the hatchlings Day 2: feed the hatchlings Day 3: feed the hatchlings Hatched two, 3 left Hatched two, 1 left Hatched two, 0 left Inspecting Ember Inspecting Skyla
Key takeaways
if/elseif/elseaccept any value: 0, empty strings, $null and empty arrays are false.switchruns every matching case; it supports -Wildcard, -Regex, script-block cases and arrays.Use foreach for collections, for for counters, while/do for conditions.
In double quotes, write
${name}:when a colon follows a variable -$name:is read as a drive-qualified name.breakleaves a loop (or a whole switch),continueskips to the next round.
Lesson quiz
7 questions · pass with 5 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write PowerShell scripts
Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.
Temperament advice
Each input line is Name temperament. Use a switch (with -Wildcard or -Regex) to print advice:
grumpyorgrouchy→Ember: approach with snacks- anything starting with
play(playful, playing...) →Glim: bring a ball sleepy→Mossback: let sleeping dragons lie- anything else →
Skyla: observe from a distance
- Morning rounds
- Evening rounds
Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.
Growth chart
The input is a hatchling’s wingspan in metres. Each year its wingspan grows by half, rounded down ([math]::Floor), but always by at least 1 m. Print a line per year until it reaches 10 m or more, then how many years that took:
1Year 0: 2 m
2Year 1: 3 m
3Year 2: 4 m
4Year 3: 6 m
5Year 4: 9 m
6Year 5: 13 m
7Fully grown after 5 years- From 2 m
- From 1 m
- Already grown
Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…