The switch Statement
Prerequisites: Conditionals: if, elseif, else
switch compares a value against several options. PowerShell's switch
is unusually powerful: it supports wildcards, regular expressions, script
blocks, and even whole arrays and files.
$day = 'Saturday'
switch ($day) {
'Saturday' { 'Weekend!' }
'Sunday' { 'Weekend!' }
'Friday' { 'Almost weekend' }
default { 'Weekday' }
}
Weekend!
Wildcards, regex, and conditions
foreach ($file in 'photo.JPG', 'report.pdf', 'notes.txt', 'archive.tar.gz') {
$type = switch -Wildcard ($file) {
'*.jpg' { 'image'; break }
'*.pdf' { 'document'; break }
'*.tar.gz' { 'archive'; break }
default { 'other' }
}
"${file}: $type"
}
$score = 84
switch ($score) {
{ $_ -ge 90 } { 'A'; break }
{ $_ -ge 80 } { 'B'; break }
default { 'F' }
}
photo.JPG: image
report.pdf: document
notes.txt: other
archive.tar.gz: archive
B
-Wildcardmatches patterns (case-insensitive by default);-Regexmatches regular expressions.- A script block as the condition (
{ $_ -ge 90 }) allows any test. - Unlike most languages, PowerShell checks every case, so several can
match.
breakstops after the first match. "${file}:"uses braces so the colon isn't read as part of the variable name.
Switching over a collection
Given an array, switch runs once per element:
switch (1, 2, 3, 4, 5) {
{ $_ % 2 -eq 0 } { "$_ is even" }
}
2 is even
4 is even
switch -File log.txt { ... } does the same for each line of a file.
Common mistakes
- Forgetting
breakwhen conditions overlap, so a value produces several outputs.