PowerShell switch Statement

PowerShell provides the switch statement in order to make decisions between different conditions which is similar to the if..else statement. The switch statement consists of test values and different conditions which are checked in order. If some of the conditions are met the condition action is executed and the next condition is checked.

switch Syntax

The switch statement syntax s like below.

switch(TEST_VALUE){
   CONDITION1 {ACTION1}
   CONDITION2 {ACTION2}
   CONDITION3 {ACTION3}
   ...
}
  • TEST_VALUE is used to check with the CONDITON’s.
  • CONDITION’s are used to check with TEST_VALUE and if one CONDITION is met the related ACTIONS are fired.
  • ACTION is fired when related CONDITION is met.

switch Example

In the following example, we provide 2 as the test value and check against the conditions. As the text value matches two conditions both condition’s actions will be executed.

switch(2){
   1 {"One"}
   2 {"Two"}
   3 {"Three"}
   2 {"Second Two"}
}
Two
Second Two

switch and break

By default the switch statement checks every condition and if matches the action is executed. Even the two or more conditions are met all of them are executed. But in some cases, we may want to only execute single condition action even if multiple matches. We can use the break keyword after every action to end the switch statement after the first match and action execution.

switch(2){
   1 {"One" ; break}
   2 {"Two" ; break}
   3 {"Three" ; break}
   2 {"Second Two" ; break}
}
Two

switch with Multiple Conditions

The switch statement can be used with multiple test values for multiple conditions. In the following example, we test multiple conditions with multiple test values 2 and 3.

switch(2){
   1 {"One"}
   2 {"Two"}
   3 {"Three"}
   2 {"Second Two"}
}
Two
Three
Second Two

Leave a Comment