PowerShell: How to Use Multiple Values in Switch Statement


You can use the following syntax in PowerShell to use a switch statement with multiple values:

switch($conference) {
    {$_ -in "North", "N", "Nor"} { "North Conference" }
    default { "Some Other Conference" }
}

This particular example looks at the string stored in the variable named $conference and does the following:

  • If the string is equal to North, N, or Nor, then return North Conference.
  • Otherwise, return Some Other Conference.

By using the -in operator, we are able to check if the string in the $conference variable belongs in a list of several strings.

The following example shows how to use this syntax in practice.

Example: How to Use Multiple Values in Switch Statement in PowerShell

Suppose we have a string variable named $conference that contains a string indicating which conference a particular sports team belongs in.

We can use a switch statement in PowerShell to return “North Conference” if the string variable contains any of the following:

  • “North”
  • “N”
  • “Nor”

We can use the following syntax to do so:

$conference = "North"

switch($conference) {
    {$_ -in "North", "N", "Nor"} { "North Conference" }
    default { "Some Other Conference" }
}

The following screenshot shows how to use this syntax in practice:

PowerShell switch statement with multiple values

The switch statement returns “North Conference” because the $conference variable contained one of the three strings that we specified after the -in operator.

Suppose instead that our $conference variable contained “South” as the string:

$conference = "South"

switch($conference) {
    {$_ -in "North", "N", "Nor"} { "North Conference" }
    default { "Some Other Conference" }
}

The following screenshot shows how to use this syntax in practice:

The switch statement returns “Some Other Conference” because the $conference variable did not contain one of the three strings that we specified after the -in operator.

Note: You can find the complete documentation for the switch statement in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply