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
$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:
$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:
$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:
$logLines = @(
'INFO user ada logged in'
'ERROR disk /dev/sda1 is 97% full'
'WARN retry 3 of 5'
)
switch -Regex ($logLines) {
'^ERROR\s+(.+)