🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Switch

A switch statement is a test that compares one value against many choices. It runs the block for the choice that matches the value.

Match a number

The switch value is 3, so the third choice runs.

$day = 3
switch ($day) { 1 { "Monday" } 2 { "Tuesday" } 3 { "Wednesday" } default { "Other day" } }

Fall back to default

The value 9 matches no choice, so the default block runs.

$day = 9
switch ($day) { 1 { "Monday" } 2 { "Tuesday" } 3 { "Wednesday" } default { "Other day" } }

Match a word

Switch also works with words, not just numbers.

$fruit = "apple"
switch ($fruit) { "apple" { "red fruit" } "banana" { "yellow fruit" } default { "unknown fruit" } }

Example

$light = "yellow"
$action = ""
switch ($light) { "red" { $action = "Stop" } "yellow" { $action = "Slow down" } "green" { $action = "Go" } default { $action = "Unknown light" } }
"Light $light means $action"

Key points

  • Switch: one value is compared with each choice in turn.
  • Match: a choice that matches runs its block.
  • Default: the default block runs when no choice matches.
  • Use switch to replace a long elseif chain that tests one value.
  • Choice: each choice is a value written before its block.

In this example, $light holds yellow and $action starts empty. The switch compares yellow with red, then yellow, and that choice sets $action to Slow down. The last line prints the light and its action.

Note

string choices match without regard to letter case, so Apple matches apple.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does this switch print? switch (2) { 1 { "one" } 2 { "two" } default { "other" } }