A switch statement uses the following generalized notation:
switch [-regex|-wildcard][-casesensitive] (<value>) { <condition> { <statements> } <condition> { <statements> } }
The casesensitive parameter applies when testing conditions against a string value.
The switch command can also be used to work on the content of a file using the following notation:
switch [-regex|-wildcard][-casesensitive] -File <Name> { <condition> { <statements> } <condition> { <statements> } }
The File parameter can be used to select from a text file (line by line).
The switch statement differs from conditions written using if-elseif in one important respect. The switch statement will not stop testing conditions unless the break keyword is used, for example:
$value = 1 switch ($value) { 1 { Write-Host 'value is 1' } 1 { Write-Host 'value is still 1' } }
Using break, as shown following, will exit the switch statement after a match:
$value = 1 switch ($value) { 1 { Write-Host 'value is 1'; break } 1 { Write-Host 'value is still 1' } }
The default keyword provides the same functionality as the else statement when using if, for example:
$value = 2 switch ($value) { 1 { Write-Host 'value is 1' } default { Write-Host 'No conditions matched' } }
A switch statement can test more than one value at once; however, break applies to the entire statement, not just a single value. For example, without break, both of the following Write-Host statements execute:
switch (1, 2) {
1 { Write-Host 'Equals 1' } 2 { Write-Host 'Equals 2' } }
If the break keyword is included as shown following, only the first executes:
switch (1, 2) { 1 { Write-Host 'Equals 1'; break } 2 { Write-Host 'Equals 2' } }