How to use the switch statement in PowerShell

Overview

The switch statement is used to switch between multiple conditions. It is similar to using multiple series of if statements. Using the switch statement in that situation is very convenient and readable.

Syntax

switch(value)
{
//conditions
}

Parameters

It takes a value as a parameter to match the condition defined in the switch statement. We can also pass a list of values.

Let's take a look at an example of this.

Example

#!/usr/bin/pwsh -Command
switch (4)
{
1 {"Condition one."}
2 {"Condition two."}
3 {"Condition three."}
4 {"Condition four."}
Default {
"No matches"
}
}

Explanation

  • Line 3: We use a switch statement and pass 4 as a value to it.
  • Lines 4–12: We define different conditions in the switch statement. The switch statement checks each condition one by one. It executes the condition that matches the value that is passed to it. It executes the Default case if no condition matches the passed value.

Free Resources