How to Use Switch in PowerShell: Syntax and Examples
In PowerShell, use the
switch statement to test a value against multiple conditions and execute code blocks for matching cases. It simplifies multiple if-elseif checks by matching input against patterns or values. The syntax includes switch, the value to test, and code blocks for each case.Syntax
The switch statement tests a value against multiple cases. Each case is a pattern or value followed by a code block. If the input matches a case, its code runs. Use default to handle unmatched cases.
- switch: keyword to start the statement
- (value): the value to test
- {}: curly braces contain cases
- case: each pattern or value to match
- default: runs if no case matches
powershell
switch ($value) { 'case1' { # code for case1 } 'case2' { # code for case2 } default { # code if no case matches } }
Example
This example shows how switch checks a variable against multiple strings and runs the matching block. If no match, it runs default.
powershell
$color = 'red' switch ($color) { 'blue' { Write-Output 'Color is blue' } 'red' { Write-Output 'Color is red' } 'green' { Write-Output 'Color is green' } default { Write-Output 'Color not recognized' } }
Output
Color is red
Common Pitfalls
Common mistakes include forgetting curly braces for cases, missing default for unmatched values, or using switch without parentheses around the value. Also, switch is case-insensitive by default, which can surprise some users.
powershell
Wrong usage (missing braces): switch ($value) 'case1' Write-Output 'No braces' # This causes error Correct usage: switch ($value) { 'case1' { Write-Output 'With braces' } }
Quick Reference
| Feature | Description |
|---|---|
| switch (value) { cases } | Basic syntax to test value against cases |
| case { code } | Code block runs if case matches |
| default { code } | Runs if no case matches |
| Case-insensitive | Matches ignore letter case by default |
| Multiple matches | Can match multiple cases if using -regex or -wildcard |
Key Takeaways
Use
switch to simplify multiple condition checks in PowerShell.Each case must have curly braces with the code to run.
Include a
default case to handle unmatched values.PowerShell
switch is case-insensitive by default.Always put the value to test inside parentheses after
switch.