Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 34 ยท Language Basics

Conditionals and Loops

Learn PowerShell control flow: if and elseif, truthiness, switch with wildcards and regex, foreach, for, while, do loops, break, continue and labels.

A script becomes useful when it can decide and repeat. PowerShell has the control flow you know from other languages: if, switch, foreach, for, while and do. It also has a few quirks that catch newcomers, mostly around what counts as true, how switch keeps matching after the first hit, and the difference between the foreach statement and the ForEach-Object cmdlet.

All the PowerShell on this page is read-only. The runnable examples are JavaScript stand-ins that model the same rules, and each one says what it models.

if, elseif and else

The condition goes in parentheses and the body in braces. Braces are required, even for one line.

POWERSHELL
$size = 42

if ($size -lt 10) {
    'small'
}
elseif ($size -lt 100) {
    'medium'
}
else {
    'large'
}

The comparison operators are the dash-words from Operators and Comparison: -eq, -ne, -lt, -gt, -like, -match and friends. A plain == or < does not compare, it just fails to parse or redirects output, so always use the dash forms. Combine tests with -and, -or, -not (or !) and group them with parentheses.

PowerShell 7 adds a ternary operator for short choices:

POWERSHELL
$label = $size -gt 50 ? 'big' : 'not big'    # PowerShell 7 and later only

What counts as true

The condition does not have to be a Boolean. PowerShell converts it.

Value Treated as
$true, any non-zero number true
0, $false, $null false
Empty string '' false
Any non-empty string, even 'false' true
Empty array @() false
Array with one item the truth of that item
Array with two or more items true

The string row is the one that bites: if ('false') { ... } runs the body. Another trap is comparing to $null with the null on the right. When the left side is an array, -eq filters the array instead of returning a Boolean, so put $null on the left: if ($null -eq $value).

switch

switch compares one value against several patterns. Unlike most languages, it keeps checking every clause after a match unless you stop it with break.

POWERSHELL
$code = 404

switch ($code) {
    200 { 'OK' }
    404 { 'Not found' }
    { $_ -ge 400 } { 'Client or server error' }
    default { 'Something else' }
}

For 404 this prints both Not found and Client or server error, because both clauses match. Inside the block, $_ holds the value being tested. A clause can be a literal, or a script block in braces that returns true or false.

Add break to stop after the first match, or continue to skip to the next input item when you are switching over an array.

POWERSHELL
switch ($code) {
    404 { 'Not found'; break }
    { $_ -ge 400 } { 'Error' }
}

Strings compare without regard to case by default. Switches change how patterns are read:

POWERSHELL
switch -Wildcard ($file) {
    '*.txt'  { 'text file' }
    '*.log'  { 'log file' }
    'report-??.csv' { 'monthly report' }
}

switch -Regex ($line) {
    '^ERROR (\d+)' { "error code $($Matches[1])" }
    '^WARN'        { 'warning' }
}

The relevant switches are -Wildcard, -Regex, -Exact (the default plain comparison), and -CaseSensitive. In -Regex mode the automatic $Matches hashtable describes the match for the current clause. If you give switch an array, it runs once per element, and -File path reads lines from a file the same way.

switch is not a ladder

Every clause tested A match does not end the switch.
break stops it Use it for first match wins.
Arrays loop Each item is tested in turn.

Forget break and two clauses can both run.

1 / 2

The stand-in below models the rules as a small function. It is not PowerShell, but it follows the same logic: case-insensitive comparison, every matching clause fires, and break stops the search.

JS A model of PowerShell's switch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Loops over collections

The foreach statement loads the whole collection and then walks it. The variable name is yours.

POWERSHELL
$names = 'Ada', 'Grace', 'Linus'

foreach ($name in $names) {
    "Hello, $name"
}

foreach ($i in 1..3) { $i * 10 }

It is a language keyword, runs quickly and lets break and continue work as expected. The ForEach-Object cmdlet (alias foreach or % when used in a pipeline) is different: it handles items as they stream through, which suits large inputs and long pipelines. The cmdlet is covered in Group-Object, Measure-Object and ForEach-Object.

POWERSHELL
1..3 | ForEach-Object { $_ * 10 }

Pick the statement when the data is already in memory and you want speed or loop control. Pick the cmdlet when you are in a pipeline and want streaming. Inside a ForEach-Object script block, return skips to the next item, but break and continue do not behave like loop control there, so do not use them in the cmdlet.

PowerShell does not enter a foreach for a $null collection, so foreach ($x in $null) { } does nothing. You can assign a loop to a variable to capture whatever it outputs, as in $doubled = foreach ($n in 1..5) { $n * 2 }.

for, while and do

Use for when you count, and while or do when you wait for a condition.

POWERSHELL
for ($i = 0; $i -lt 5; $i++) {
    "step $i"
}

$tries = 0
while ($tries -lt 3) {
    $tries++
}

do {
    $answer = Read-Host 'Type yes'
} until ($answer -eq 'yes')

do { } while (cond) repeats while the condition is true. do { } until (cond) repeats until it becomes true, so it is the same loop with the test inverted. Both run the body at least once, unlike plain while, which can run zero times.

break, continue and labels

break leaves the loop. continue skips to the next pass. When loops are nested, put a label before the outer one and name it to jump out of both.

POWERSHELL
:rows foreach ($row in 1..3) {
    foreach ($col in 1..3) {
        if ($col -eq 2) { continue }          # next column
        if ($row -eq 2) { continue rows }     # next row
        if ($row -eq 3) { break rows }        # leave both loops
        "r$row c$col"
    }
}

Mind a classic mistake: an infinite while ($true) with no break or exit condition. Always give the loop a way out, such as a counter, a timeout or a status check.

This second stand-in models the three loop forms and a labeled exit. The JavaScript versions use the same structure, so you can compare the logic line by line.

JS Loops and loop control compared

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The labeled break and the do-while behavior are the same in both languages. The truthiness helper is a model of PowerShell's rules, because JavaScript's own rules differ (an empty array is true in JavaScript, false in PowerShell).

if ($list) is a quick way to test "is this non-empty", but it fails for a list that holds a single 0 or empty string. Use $list.Count -gt 0 when the contents could be falsy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A switch has two clauses that both match the input, and neither contains break. What happens?

    switch tests every clause. Add break (or continue, for array input) when you want first match wins.
  2. 2. What does if ('false') { 'yes' } print?

    PowerShell converts non-empty strings to true. Only the empty string is false.
  3. 3. Which loop always runs its body at least once?

    do loops test the condition after the body. while, for and foreach test before, so they can run zero times.
  4. 4. Which switch option lets a clause such as '*.log' match file names using star and question mark?

    -Wildcard reads patterns like -like does. -Regex reads them as regular expressions, and -Exact is the plain default.
  5. 5. What is the safest way to test a value against null?

    With null on the left, an array on the right is not filtered, so the result is always a real Boolean. A single = would assign, not compare.

Summary

  • if, elseif and else use parentheses for the test and braces for the body. PowerShell 7 adds ? :.
  • Empty strings, 0, $null and empty arrays are false. Non-empty strings are true, even 'false'.
  • switch checks every clause, so add break for first match wins. Use -Wildcard, -Regex and -CaseSensitive to change how patterns match.
  • The foreach statement is fast and supports break and continue. ForEach-Object streams in a pipeline.
  • for counts, while may run zero times, do runs at least once. Labels let break and continue target an outer loop.

Next, package your logic into reusable code with Functions and Parameters.