PowerShell Switch Statement: The Beginner’s Guide!

A switch statement allows you to specify a set of conditions to test against and execute a different set of codes for each condition. This can be extremely useful when you need to take different actions based on different data. The switch statement in PowerShell is similar to the switch statement in other programming languages. It takes an expression as input, and then compares the value of the expression to a list of cases. If a match is found, the code block associated with that case is executed. If no match is found, an optional default case can be used to execute a code block. Whether you are a beginner or an experienced PowerShell user, this guide will help you master the Switch statement and leverage its capabilities in your scripts.

Let’s see an overview of what the PowerShell switch statement is and how it works, as well as some examples of how it can be used in your PowerShell scripts. The syntax for using the switch statement is fairly straightforward. It starts with the keyword “switch” followed by an expression in parentheses that contains the value you want to compare against. Then, each condition is evaluated in order until one of them matches the expression value, and its associated code block executes. If none of the conditions match, then an optional “default” code block can be used instead.

The syntax of a switch statement in PowerShell

Let’s take a closer look at the syntax of a switch statement in PowerShell.

Expression

The expression in the switch statement can be any valid PowerShell expression. This can include variables, cmdlet output, or any other PowerShell expression.

Values

The values in the switch statement can be any valid PowerShell expression that evaluates to a constant value. This can include strings, numbers, or any other constant value.

Code blocks

The code blocks in the switch statement are the lines of PowerShell code that are executed when the expression matches the corresponding value. Each code block must be enclosed in curly braces {}.

The basic syntax of a switch case statement in PowerShell is as follows:

switch (expression)
{
    value1 {code block}
    value2 {code block}
    value3 {code block}
    default {code block}
}

PowerShell switch default block

The default case in a switch statement is used to handle situations where none of the cases match the evaluated expression. It serves as a fallback option when no specific action needs to be taken for unmatched values.

PowerShell switch parameters

In PowerShell, the Switch statement allows you to specify different actions to be taken based on the different values of a single expression or variable. The Switch statement has several parameters that you can use to customize its behavior.

Here is a list of some of the parameters that you can use with the Switch statement:

  • -Regex: This parameter allows you to use regular expressions to match patterns in the values being compared.
  • -Wildcard: This parameter allows you to use wildcard characters (such as * and ?) to match patterns in the values being compared.
  • -Exact: This parameter specifies that the values being compared should be matched exactly, without any wildcard or regex matching.
  • -CaseSensitive: This parameter specifies that the values being compared should be matched in a case-sensitive manner.
  • -File: This parameter specifies a file containing a list of values to be matched. Each value in the file should be on a separate line.

PowerShell switch examples

The switch statement is similar to the if statement, but it allows you to test for multiple conditions and execute different code blocks for each condition. Switch statements can be used with any data type, but they are most commonly used with string data. To illustrate the usage of PowerShell switches, let’s consider a simple example where we determine the day of the week based on a numeric value. Here’s the code:

$day = Read-Host "Enter the Day number (1-7):"

switch ($day) {
    1 { Write-Host "It's Monday." }
    2 { Write-Host "It's Tuesday." }
    3 { Write-Host "It's Wednesday." }
    4 { Write-Host "It's Thursday." }
    5 { Write-Host "It's Friday." }
    6 { Write-Host "It's Saturday." }
    7 { Write-Host "It's Sunday." }
    default { Write-Host "Invalid input. Please enter a number between 1 and 7." }
}

In this example, the user is prompted to enter a number between 1 and 7. The switch statement evaluates the input value and displays the corresponding day of the week. If an invalid input is provided, the default case is executed, and an error message is displayed.

powershell switch

Here is an example of a simple switch statement with a predefined value in PowerShell:

$value = "apple"

switch ($value) {
    "apple" {
        Write-Host "The value is an apple"
    }
    "banana" {
        Write-Host "The value is a banana"
    }
    default {
        Write-Host "The value is something else"
    }
}

#Output: The value is an apple

In this example, the value of the variable $value is set to “apple”. The switch statement then compares the value of $value to the cases “apple” and “banana”. Since the value of $value is “apple”, the code block associated with the “apple” case is executed, and the output will be “The value is an apple”.

PowerShell switch

Comparing Values with the Switch Statement

In addition to testing against a single value, the Switch statement can also compare numeric values. This allows you to perform different actions based on different ranges of values. Here is how you can validate user input with multiple conditions using the Switch statement.

$input = 10

Switch ($input) {
    { $_ -lt 10 } {
        Write-Host "The value is less than 10."
    }
    { $_ -ge 10 -and $_ -lt 20 } {
        Write-Host "The value is between 10 and 20."
    }
    { $_ -ge 20 -and $_ -lt 30 } {
        Write-Host "The value is between 20 and 30."
    }
    { $_ -ge 30 } {
        Write-Host "The value is greater than or equal to 30."
    }
    default {
        Write-Host "The number is not valid" -f Red
    }
}

In this example, the variable $input is set to 10. The Switch statement compares this value against each condition in the switch block. The first condition tests if the value is less than 10, the second condition tests if the value is between 10 and 20, the third condition tests if the value is between 20 and 30, and the fourth condition tests if the value is greater than or equal to 30. We also have the default block to match with any other value.

PowerShell switch statement with wildcard

You can also use wildcard patterns in your switch cases to match multiple values. For example:

$value = "orange"

switch -wildcard ($value) {
    "a*" {
        Write-Host "The value starts with the letter 'a'"
    }
    "b*" {
        Write-Host "The value starts with the letter 'b'"
    }
    "*e" {
        Write-Host "The value ends with the letter 'e'"
    }
    default {
        Write-Host "The value does not match any patterns"
    }
}

In this example, the value of $value is set to “orange”. The switch statement compares the value of $value to the cases using a wildcard string pattern. Since the value of $value ends with the letter “e”, the code block associated with the “*e” case is executed, and the output will be “The value ends with the letter ‘e'”. Here is a real-world example of using the wildcard in a switch statement in PowerShell:

$Filepath = "C:\Reports\sales-2022.pdf"

switch -wildcard ($FilePath) {

  "*sales*" {
    Write-Output "Sales report detected"
    Move-Item $Filepath "C:\Sales\Reports\"
    break;
  }

  "*inventory*" {
    Write-Output "Inventory report detected"
    Move-Item $Filepath "C:\Inventory\Reports\"  
    break;
  }

  default {
    Write-Output "PDF report detected"
    Move-Item $filepath "C:\Reports\PDFReports\" 
  }
}

The switch statement in PowerShell also has several additional parameters that can make it even more powerful and flexible. E.g. -CaseSensitive -Exact -Parallel -Wildcard, etc.

Switch statement to Search Content in File

You can use the -File parameter of the switch statement to search for specific keywords in a text file. Here is an example:

Switch -File "C:\Logs\AppLog.txt" {
    {$_ -match "Error"} {
        Write-Host "The log file contains Errors"
    }
    {$_ -match "warning"} {
        Write-Host "The log file contains Warnings"
    }
    {$_ -match "information"} {
        Write-Host "The log file contains information"
    }
    default {
        Write-Host -f Yellow "The log file does not contain any specific keywords!"
    }
}

This script loops through each line of the given text file and the match clause checks if the line matches with the given keyword.

Switch with RegEx Example

One such option is the -regex parameter, which allows you to use regular expressions to match cases in your switch statement. For example:

#$value = "123-456-7890"
$value = "Salaudeen@crescent.com"

switch -regex ($value) {
    "\d{3}-\d{3}-\d{4}" {
        Write-Host "The value is a phone number"
    }
    "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" {
        Write-Host "The value is an email address"
    }
    default {
        Write-Host "The value does not match any patterns"
    }
}

In this example, the value of $value is set to a phone number. The switch statement compares the value of $value to the cases using regular expressions. Since the value of $value matches the regular expression for a phone number, the code block associated with that case is executed, and the output will be “The value is a phone number”.

PowerShell switch with multiple values (Arrays)

You can use the Switch statement to perform different actions based on the different values of a single expression or variable. To specify multiple values for which a particular action should be taken, you can use a comma-separated list of values inside the curly braces of the Switch statement.

Here is an example of how you can use the Switch statement with multiple values:

$value = 1, 2

Switch ($value) {
    1 { Write-Host "The Value contains 1" }
    2 { Write-Host "The Value contains 2" }
    3 { Write-Host "The Value contains 3" }
    default { Write-Host "Value is something else" }
}

The above script passes an Array Value to switch. This script will output “The Value contains 1” and “The Value contains 2”. Let’s see another example with string array:

$Fruits = "apple", "orange", "banana"

Switch ($fruits) {
    "apple" {
        Write-Host "We have an apple."
    }
    "orange" {
        Write-Host "We have an orange."
    }
    "banana" {
        Write-Host "We have a banana."
    }
    default {
        Write-Host "The fruit is not recognized."
    }
}

In this example, the variable $fruits contains an array of fruits. The Switch statement compares each value in the array against each case in the switch block. Since the array contains the values “apple”, “orange”, and “banana”, the corresponding actions “We have an apple”, “We have an orange”, and “We have a banana” are executed. The output of this script will be:

We have an apple.
We have an orange.
We have a banana.

Switch Statement with “break” in PowerShell

In PowerShell, you can use the break keyword to exit from a loop. In the context of switch, it’s used to break and exit from the switch statement early. When the break statement is encountered inside a switch statement, it immediately exits the switch and continues execution at the next statement after the switch. Here is an example of how you can use the break statement inside a Switch statement in PowerShell to stop on the first match:

$value = 1, 2

$Result = Switch ($value) {
    1 { Write-Host "The Value contains 1"; break }
    2 { Write-Host "The Value contains 2"; break }
    3 { Write-Host "The Value contains 3"; break }
    default { Write-Host "Value is something else" }
}

#Get the Result
$Result

This will result in “The value contains 1” alone. The break just completes the current item, breaks all processing, and exits the switch statement. To understand the break statement better, here is another example:

PowerShell Switch statement without break statement:

$number = 1

Write-Output "Without break:"
switch ($number) {
  { $_ -lt 100 } {" Less than 100 "}
  { $_ -lt 10 } {" Less than 10"}  
  { $_ -lt 5 } {" Less than 5"}
}

Result:

 Less than 100 
 Less than 10
 Less than 5

PowerShell Switch statement with break statement:

$number = 1

Write-Output "Without break:"
switch ($number) {
  { $_ -lt 100 } {" Less than 100 "; Break}
  { $_ -lt 10 } {" Less than 10"; Break}  
  { $_ -lt 5 } {" Less than 5"; Break}
}

Result:

 Less than 100

PowerShell Switch with Multiple Conditions

Similarly, you can use the switch statement with multiple conditions, E.g.,

$value = 4

Switch ($value) {
    1 { Write-Host "Value is 1" }
    2 { Write-Host "Value is 2" }
    {($_ -eq 3) -or ($_ -eq 4) -or ($_ -eq 5)} {"It is 3, 4, or 5."}
    default { Write-Host "Value is something else" }
}

The shorter version for multiple cases would be:

$value = 5

Switch ($value) {
    1 { Write-Host "Value is 1" }
    2 { Write-Host "Value is 2" }
    {3, 4, 5) } {"It is 3, 4, or 5."}
    default { Write-Host "Value is something else" }
}

In this example, the Switch statement checks the value of the $value variable. If the value of $value is 1, it will output “Value is 1”. If the value is 2, it will output “Value is 2”. In case, the value is 3, 4, or 5, it will output “Value is 3, 4, or 5”. If the value is none of these, it will output “Value is something else”.

Case Sensitivity in the Switch Statement

Finally, Switch parameters are case-insensitive by default. This means that it will match string values regardless of their case. In other words, lower case is equal to upper case! However, you can change this behavior and make the Switch statement case-sensitive by using the -CaseSensitive parameter.

Use the CaseSensitive parameter to perform a case-sensitive match of the test value. E.g.,

switch -casesensitive ("Banana") {
	"banana" { "Given Value is $_"; break }
    "mango" { "Given Value is $_"; break }
    "Banana" { "Given Value is $_"; break }
    default { "Some other fruit fruit" }
}

In this example, the given value is set to “Banana”. By using the -CaseSensitive parameter, we make the Switch statement case-sensitive. This means that it will only match the case “Banana” and not “banana”.

Switch statement with multiple actions per value

You can use a switch statement to evaluate a value and perform different actions based on its value. By default, a switch statement executes code blocks for each matching case value. However, if you want to perform multiple actions for a specific case value, you can enclose those actions in a script block ({ }). Here’s how you can use a switch statement with multiple actions per value:

$day = Get-Date -UFormat %A

switch ($day) {
  "Saturday" {
    Write-Output "It's the weekend!"
    Write-Output "Sleeping in today."
  }
  "Sunday" {
    Write-Output "It's the weekend!"
    Write-Output "Going to brunch." 
  }
  default {
    Write-Output "It's a weekday."
  }
}

PowerShell switch vs. if statement – Which is better?

When deciding between a switch statement and an if statement, it’s important to consider the complexity of the conditions you need to evaluate. Here are some points to consider:

What is the difference between switch and else if in PowerShell? Well, in general, if you’re testing a single variable against many different values, switch might be a better choice. If you’re testing many variables, or have more complex logical conditions, then “if” might be a better choice. It really depends on the specific use case.

  • Complexity of Conditions: If there are many conditions to check or the conditions are based on multiple different values of a single variable, a switch statement can be more readable and easier to manage than an if statement. Switch statements are designed to handle multiple values elegantly, especially for cases where there are more than two conditions to check.
  • Performance: Switch statements can be faster when there are many conditions because switch uses a hashtable for matching. This can result in performance gains when dealing with a large number of conditions.
  • Default Case Handling: Switch statements provide an easy way to handle a default case when none of the specified conditions are met using default.
  • Complex Logic: On the other hand, if statements are better for more complex logic, where you might need to check multiple different variables or conditions at once, or when the conditions involve logical operators (like && and ||).
  • Readability: For simple conditions, if statements can be more straightforward and easier to understand, particularly for those new to programming.
  • Flexibility: If statements offer more flexibility for conditions involving ranges, or conditions that can’t easily be expressed as a simple list of values.

Wrapping up

Mastering PowerShell switches is a crucial skill for any PowerShell scripter. They provide a flexible and efficient way to handle complex branching logic based on different conditions. There are many other options and features available for the switch statement in PowerShell, including the ability to specify multiple values for a case, the ability to use case statements to specify more complex conditions, and the ability to use the break statement to exit a switch block early. It is similar to an if/else block, but with a few added benefits. For example, it can be used to evaluate multiple conditions at once without needing to nest if/else statements inside each other.

Overall, the switch statement is a powerful and flexible tool for controlling the flow of your PowerShell scripts and automating tasks based on different values and conditions. It is an essential part of the PowerShell language and is a key feature for anyone who is working with PowerShell.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *