Um momento
0x90Lesson 10 of 17

Conditions and loops

Make decisions with if and switch, and repeat work with foreach, for, while and do loops.

28 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • 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 of 8 sortedScore 0/0
  • “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 -Wildcard uses -like patterns; switch -Regex uses regexes (and fills $Matches).
  • A case can be a script block that tests $_: { $_ -gt 10 } { 'big' }.
  • default runs when nothing else matched.
  • Give switch an array and it processes each element in turn - a loop and a decision in one.
switch.ps1
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}
Output
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

LoopUse 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.

loops.ps1
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}
Output
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/else accept any value: 0, empty strings, $null and empty arrays are false.

  • switch runs 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.

  • break leaves a loop (or a whole switch), continue skips 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.

Exercise 1

Temperament advice

+25 XP

Each input line is Name temperament. Use a switch (with -Wildcard or -Regex) to print advice:

  • grumpy or grouchy → 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
script.ps1
Loading editor…

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.

Exercise 2

Growth chart

+25 XP

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
script.ps1
Loading editor…

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…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: