TExcelTAD
Home › PowerShell › PowerShell Switch

PowerShell Switch

The switch statement compares one value against a list of cases and runs the code of each case that matches. PowerShell's switch is much more powerful than in most languages: it can match wildcards and regular expressions, use script-block conditions, and even loop over arrays and files.

Basic switch

powershell · try it yourself
$day = 'Saturday'

switch ($day) {
    'Saturday' { 'Weekend!' }
    'Sunday'   { 'Weekend!' }
    'Friday'   { 'Almost there' }
    default    { 'Working day' }
}
Weekend!

default runs when no other case matched. Matching is case-insensitive by default, so 'saturday' would match too.

All matches run (use break)

Unlike if/elseif, a switch doesn't stop at the first match. Every matching case runs, unless one of them calls break:

powershell · try it yourself
$number = 15

switch ($number) {
    { $_ % 3 -eq 0 } { 'divisible by 3' }
    { $_ % 5 -eq 0 } { 'divisible by 5' }
    { $_ -gt 10 }    { 'greater than 10' }
}
'---'
switch ($number) {
    { $_ % 3 -eq 0 } { 'divisible by 3'; break }
    { $_ % 5 -eq 0 } { 'divisible by 5' }
}
divisible by 3
divisible by 5
greater than 10
---
divisible by 3

The cases above are script blocks: a condition in braces where $_ is the value being tested. Any expression that returns true counts as a match.

Wildcards and regular expressions

Add -Wildcard or -Regex to change how string cases are compared:

powershell · try it yourself
$files = 'report.pdf', 'photo.JPG', 'notes.txt', 'archive.tar.gz'

foreach ($file in $files) {
    $kind = switch -Wildcard ($file) {
        '*.pdf'         { 'document' }
        '*.jpg'         { 'image' }
        '*.txt'         { 'text' }
        default         { 'other' }
    }
    '{0,-15} {1}' -f $file, $kind
}
report.pdf      document
photo.JPG       image
notes.txt       text
archive.tar.gz  other

With -Regex, the $Matches variable is filled in for each matching case, so you can pull out parts of the input:

powershell · try it yourself
$logLines = @(
    'INFO  user ada logged in'
    'ERROR disk /dev/sda1 is 97% full'
    'WARN  retry 3 of 5'
)

switch -Regex ($logLines) {
    '^ERROR\s+(.+)
  

 { "Problem: $($Matches[1])" }
    '^WARN\s+retry (\d+) of (\d+)' { "Retrying ($($Matches[1])/$($Matches[2]))" }
    '^INFO' { 'info line skipped' }
}
info line skipped
Problem: disk /dev/sda1 is 97% full
Retrying (3/5)

Switching over arrays

When you give switch an array, it processes each element in turn, like a loop. Inside, continue moves on to the next element and break stops the whole switch:

powershell · try it yourself
$readings = 21, 24, -999, 23, 99, 22

$sum = 0
switch ($readings) {
    -999           { 'skipping a sensor error'; continue }
    { $_ -gt 50 }  { "stopping at suspicious value $_"; break }
    default        { $sum += $_ }
}
"Sum of good readings: $sum"
skipping a sensor error
stopping at suspicious value 99
Sum of good readings: 68

Other options

Option Effect
-CaseSensitive 'A' no longer matches 'a'
-Exact plain string equality (the default)
-Wildcard cases are -like patterns
-Regex cases are regular expressions, sets $Matches
-File path processes each line of a text file
powershell · try it yourself
Set-Content ./hosts.txt "web01`ndb01`n# comment`nweb02"
switch -Wildcard -File ./hosts.txt {
    '#*'    { continue }
    'web*'  { "web server: $_" }
    'db*'   { "database: $_" }
}
web server: web01
database: db01
web server: web02

Note: switch is a statement that returns output, so you can assign it like $kind = switch (...) { ... }, as in the wildcard example.

Test yourself

With value 6 and cases { $_ -gt 1 } and { $_ -gt 5 } (no break), how many cases run?

  1. 0
  2. 1
  3. 2
  4. It is an error

Which switch option lets you use patterns like '*.log'?

  1. -Regex
  2. -Wildcard
  3. -Like
  4. -Pattern

What does continue do inside a switch over an array?

  1. Stops the switch
  2. Skips to the next array element
  3. Runs the default case
  4. Restarts from the first element