PowerShell Switch Statement: A Comprehensive Guide

Published:25 March 2020 - 10 min. read

The concept of conditional logic in programming is not anything new. Conditional logic is a fancy term for first checking for a condition (if something happened) and then doing something as a result of that condition.

Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.

For example, in a script that creates a report of all disk space usage, conditional logic is useful for evaluating the free space status. Based on a defined threshold, the free disk space status may be tagged as normal, warning, or critical when evaluated using conditional logic.

Most, if not all, languages use their own version of the conditional logic construct. Think of if/then statement. One of the conditional logic constructs available in PowerShell is the switch statement.

In this article, you will learn what the PowerShell switch statement is, understand its syntax and how it works. You will also learn from the PowerShell switch examples some of the different ways that you can use conditional logic handling in your scripts.

Understanding the Basic PowerShell Switch Statement

The PowerShell switch statement is a conditional logic statement used for evaluating one or more conditions. It is comparable to the PowerShell If statement. They are both used for the same purpose – to test conditions before running actions. Why use the switch statement over if statements? When you must check multiple conditions.

Using an if statement for multiple conditions can be tedious and lengthy. Evaluating multiple conditions is easier with the use of switch statements instead. Please refer to the switch statement syntax below.

Switch (<test-value>)
{
    <condition> {<action>}
    <condition> {<action>}
}

As you can see from the syntax above, the switch statement starts with  Switch and the value to test is enclosed in parenthesis (). Then, inside the curly brackets {} are the conditions or case, and actions list.

A condition or case can be a value or an expression. An action can also be a value to return, or an expression to run specified actions.

The code below prompts the user to input a number. That number is stored in the $num variable. Then, the value of $num is evaluated by the conditions and then runs the associated action when the test value and the condition matched.

$num = Read-Host "Enter a number"
Switch ($num)
{
    1 {'Run Action 1'}
    2 {'Run Action 2'}
    3 {'Run Action 3'}
}

When you run the code above in PowerShell, the expected output is shown below.

Using switch to test number input
Using switch to test number input

So what happened? The value of the $num variable matched a PowerShell switch case from the list of conditions ( 3 ), whose action is to output Run Action 3 on the screen.

Defining a Default Match Clause

The switch statement below only have three conditions. Those three conditions evaluate if the value of the $num variable is 1, 2 or 3.

$num = Read-Host "Enter a number"
Switch ($num)
{
    1 {'Run Action 1'}
    2 {'Run Action 2'}
    3 {'Run Action 3'}
}

How about if the value of $num does not match any of the conditions? In that situation, when the test value does not match any of the conditions, the code will do nothing.

See the example below when the code is run in PowerShell, and the user enters the number 4. The switch statement ends and returns nothing. That is because there is no condition to evaluate the input value of 4.

Switch test returns nothing
Switch test returns nothing

Instead of returning nothing, it would be nice if the switch statement runs a default action for when no condition is matched. That’s where the default match clause comes into play.

See the modified example code below. A default match clause is added at the end to display a default message if the input test value does not match any of the conditions. Default is the equivalent of the Else clause in the If statement.

$num = Read-Host "Enter a number"
Switch ($num)
{
    1 {'Run Action 1'}
    2 {'Run Action 2'}
    3 {'Run Action 3'}
    default {'No Action'}
}

And when the modified code is run in PowerShell, the expected output is shown below.

Switch statement with a default match clause
Switch statement with a default match clause

Evaluating Multiple Test Values

So far, you’ve seen how the PowerShell switch statement is used to evaluate a single test value. But, the switch statement can also test multiple test values against a list of conditions.

In this next example, the code prompts the user to enter two numbers. The switch statement then tests the two values, one at a time according to their ordinal places.

$num1 = Read-Host "Enter first number"
$num2 = Read-Host "Enter second number"
switch ($num1, $num2)
{
    1 {"It is one." }
    2 {"It is two." }
    3 {"It is three." }
    4 {"It is four." }
    default {"Not found"}
}
Switch with multiple test values
Switch with multiple test values

You can also pass an array as the test value for the switch statement like you see from the example below.

$arrayNum = @(1,3)
switch ($arrayNum)
{
    1 {"It is one." }
    2 {"It is two." }
    3 {"It is three." }
    4 {"It is four." }
    default {"Not found"}
}

Matching Multiple Conditions

Unlike the If statement where the statement exits when the first match is found, the switch statement will test all conditions even after the first match is found. This makes it possible for the switch statement to match the test value with multiple conditions.

In this example below, the test value banana matches multiple conditions inside the switch statement.

switch ("banana") {
    "apple" { "I have an apple" }
    "orange" { "I have an orange" }
    "banana" { "I have a banana" }
    "mango" { "I have a mango" }
    "banana" { "I have a banana, again!" }
    default { "I don't have that fruit" }
}

The output below shows that the test value banana matched two conditions that triggered the corresponding actions.

Switch statement matches multiple conditions
Switch statement matches multiple conditions

Terminating a Powershell Switch with the Break Statement

In the previous section, you’ve seen how the test value can match multiple conditions in a switch statement. Depending on the purpose of your script, this behavior of matching more than one condition may be OK.

But, you can have more control of the script if you can instruct the switch statement to break its flow when the test value already found its first match. This is where the break statement is useful.

In this example, the same code in the previous section is used but modified to include the break statement. As you can see, each condition is followed by the break statement, which causes the switch statement to terminate once the test value matched a condition.

switch ("banana") {
    "apple" { "I have an apple"; break }
    "orange" { "I have an orange"; break }
    "banana" { "I have a banana"; break }
    "mango" { "I have a mango"; break }
    "banana" { "I have a banana, again!"; break }
    default { "I don't have that fruit" }
}

When you put the code above in action, the below output is what it would look like. Although two conditions that evaluate the test value “banana”, only the result of the first matching condition is returned.

Switch statement terminated with the break statement
Switch statement terminated with the break statement

Exploring More of the Powershell Switch Statement

The previous sections showed you the bare essentials about the switch statement. But the switch statement is more than just the basics. At times you may need to do more with it than just matching simple strings and numerical values. And in the next sections, you’ll learn about the different parameters or options available with the switch statement.

Different Switch Statement Parameters

There are five parameters to the switch statement. These parameters are:

  • exact – This applies to string test values only. If this parameter is used, it indicates that the condition will only apply if the statement exactly matches the test value. On the other hand, if this parameter is not used, the switch statement behaves as though the exact parameter is used.
  • casesensitive – This parameter is for string test values. Using this parameter indicates that the switch statement will perform a case sensitive match.
  • regex – Using this parameter indicates that the switch will perform a regular expression matching. This statement only applies to string test values.
  • wildcard – This parameter also only applies to string test values. Using this parameter indicates that the switch statement will accommodate testing for wildcard string. The comparison to be performed will be case-insensitive.
  • file – This parameter is used if you plan to use the contents of a file as input instead of specifying the test value outright. The contents of the file will be evaluated line by line.

Each parameter makes the switch statement behave differently. Some parameters can be used together, and some override others. The wildcard and regex parameters conflict with each other. When both parameters are used, only the last parameter is used.

Full Switch Statement Syntax

Building upon the previous section discussing the switch statement parameters, the lines of code below would probably look familiar to you by now.

switch [-regex|-wildcard|-exact][-casesensitive] (<value>)
{
    "string"|number|variable|{ expression } { statementlist }
    default { statementlist }
}
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename>
{
    "string"|number|variable|{ expression } { statementlist }
    default { statementlist }
}

You’ll notice from the syntax block above, the string number variable expression statementlist. That particularly arranged set of words means that the Powershell switch statement accepts string, number, variable and expression as test values. Then the statementlist is where the action(s) to execute when the condition matched is listed.

Using the -File Parameter

In this example, the switch statement uses the file parameter to use a file as the input for the test value.

Below is an example of the text file named random.txt containing a list of twenty random sentences.

She can live her life; however, she wants as long as she listens to what I have to say.
Carol drank the blood as if she were a vampire.
Had he known what was going to happen, he would have never stepped into the shower.
The father died during childbirth.
My dentist tells me that chewing bricks is very bad for your teeth.
When motorists sped in and out of traffic, all she could think of was those in need of a transplant.
He would only survive if he kept the fire going and he could hear thunder in the distance.
The view from the lighthouse excited even the most seasoned traveller.
It was the best sandcastle he had ever seen.
As the years pass by, we all know owners look more and more like their dogs.
Buried deep in the snow, he hoped his batteries were fresh in his avalanche beacon.
You can't compare apples and oranges, but what about bananas and plantains?
She saw no irony asking me to change but wanting me to accept her for who she is.
I don’t respect anybody who can’t tell the difference between Pepsi and Coke.
Dan took the deep dive down the rabbit hole.
On a scale from one to ten, what's your favourite flavour of random grammar?
He hated that he loved what she hated about hate.
I covered my friend in baby oil.
He figured a few sticks of dynamite were easier than a fishing pole to catch fish.
The Japanese yen for commerce is still well-known.

Next, the code below will test each line of the random.txt file and display only the sentences that contained the word “she”.

switch -file .\random.txt {
    {$_ -match 'she'} { $_ }
}

When the code above is run, it will show the below output. As you can see, out of the twenty sentences in the random.txt file, only the sentences with the word “she” is returned.

Switch statement using the file parameter
Switch statement using the file parameter

Using the -Wildcard Parameter

Using the same file in the previous example named random.txt, this next example will use the -wildcard parameter to evaluate the sentences inside the random.txt file contained the word She. And to make sure that only the word with uppercase S is returned, the -casesensitive parameter is also used.

switch -casesensitive -wildcard -file .\random.txt {
    "*She*" { $_ }
}

After running the code above, the expected output is shown below. As you can see, only the sentences with matching the wildcard search for She (with an uppercase S) is returned.

Switch statement using the WildCard and CaseSensitive parameters
Switch statement using the WildCard and CaseSensitive parameters

Using the -CaseSensitive Parameter

This example uses the CaseSensitive parameter to perform a case-sensitive search of the test value Banana. Looking closely into the code below, there are two conditions for the word banana, but one of them start with an uppercase B.

switch -casesensitive ("Banana") {
    "apple" { "I have $_"; break }
    "orange" { "I have $_"; break }
    "banana" { "I have $_"; break }
    "mango" { "I have $_"; break }
    "Banana" { "I have $_"; break }
    default { "I don't have that fruit" }
}

Running the code above, the expected output is shown below.

Switch statement using the casesenstive parameter
Switch statement using the casesenstive parameter

Using the -RegEx Parameter

This example demonstrates how to use the -RegEx parameter to perform regular expression match to determine if the test value is an email address.

The text below is the regular expression that will be used to evaluate the test value. This regular expression is saved in a file called RegExp.txt.

(?:[a-z0-9!#$%&'+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])")@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\[\x01-\x09\x0b\x0c\x0e-\x7f])+)])

Below is the list of supposedly email address to validate. This list is saved in a file called email.txt.

[email protected]
[email protected]
www.google.com
[email protected]
smtp.office365.com

Referencing the code below, the first line will import the contents of the RegExp.txt and store it in the $RegExp variable. Then, the Powershell switch statement uses the email.txt file as the input for test values as indicated by the -file parameter.

$RegExp = Get-Content .\RegExp.txt
switch -regex -file .\email.txt {
    $RegExp {"[$_] is an email address"}
    Default {"[$_] is NOT an email address"}
}

Once the code above is run in PowerShell, only the test value that matches the regular expression stored in the $RegExp will be validated. If the test value did not match the regular expression, the Default clause would be triggered. See the sample output below.

Using Switch RegEx to validate email addresses
Using Switch RegEx to validate email addresses

Conclusion

In this article, you’ve learned the basics of the switch statement and how it can be used to evaluate conditions before running any corresponding code. The switch statement is also capable of performing more complex tests like evaluating regular expressions and wildcards.

The parameters can also be used together to combine their functionalities for a more controlled result. I hope that in this article, you have gained a new item in your PowerShell toolbox for when you need to write scripts that involve conditional logic and decision making.

Perhaps your next project would be to create a script that reports unhealthy systems or monitoring event logs while using the switch statement. There are a lot of possible uses for the PowerShell switch statement and keep practicing.

Happy scripting!

Further Reading

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!