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 code 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.

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.

PowerShell switch examples

Switch statements can be used with any data type, but they are most commonly used with string data. Here is an example of a simple switch statement 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

You can validate user input with multiple conditions using the Switch statement.

$input = 10
switch ($input) {
    {$input -ge 1 -and $input -le 10} {
        Write-Host "The number is valid" -f Green
    }
    default {
        Write-Host "The number is not valid" -f Red
    }
}

In this example, the switch statement is used to validate user input to ensure that it is a number between 1 and 10.

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 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 wildcard patterns. 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'”.

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 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 = "[email protected]"

switch -regex ($value) {
    "\d{3}-\d{3}-\d{4}" {
        Write-Host "The value is a phone number"
    }
    "^[A-Za-z0-9._%+-][email protected][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 multiple values

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”.

Switch Statement with “break” in PowerShell:

In PowerShell, you can use the break statement to exit a 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.

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”. If 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”.

Finally: Switch parameters are case-insensitive by default. Use the CaseSensitive parameter to perform a case-sensitive search 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" }
}

Wrapping up

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. Additionally, it can be used to quickly check for values in arrays or collections without having to write a loop.

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 - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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