PowerShell switch
switch compares one value against several possibilities. It replaces a stack of elseif branches with something you can actually read.
Documentation: Microsoft Learn
Overview
By default it matches exact values, case-insensitively for strings. Switches change that: -Wildcard matches with * and ?, -Regex matches with regular expressions, and -CaseSensitive requires an exact case match. default catches anything unmatched.
The behaviour that catches people out is that PowerShell's switch does not stop at the first match. Every matching branch runs. If you want the C-style behaviour of stopping after one, put break at the end of the branch. This is a feature when you want overlapping patterns to all apply, and a bug when you did not expect it.
switch also enumerates collections. Feed it an array and it runs the whole switch once per element, with $_ holding the current item. That makes it a compact way to classify a list.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$day = 'Saturday'
switch ($day) { 'Saturday' { 'Weekend' } 'Sunday' { 'Weekend' } default { 'Weekday' } }- Stage 1$day
Positional values or no named parameters
An example to inspect
Preview the example. Sign in for the full lesson and activities.
$day = 'Saturday'
switch ($day) { 'Saturday' { 'Weekend' } 'Sunday' { 'Weekend' } default { 'Weekday' } }What happens
$day holds Saturday, and the switch compares it against the listed values. The Saturday branch matches and produces Weekend. Add a second branch that also matches and run it again to see both fire, which is the fall-through behaviour that surprises people coming from C or Java.
Worth remembering
- switch matches exactly and case-insensitively by default.
- -Wildcard, -Regex and -CaseSensitive change the matching.
- Every matching branch runs unless you add break.
- Given an array, switch runs once per element with $_ set.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
Matches a string against several values and returns the matching branch.
Show reference output
Illustrative output · values vary by environment
Weekend