Posey's Tips & Tricks

How To Use a Switch to Simplify Your PowerShell Scripts

Discover how to declutter and simplify your PowerShell scripts using switch statements, enhancing both readability and debuggability while learning tips for managing multiple and no-match scenarios.

If you write a lot of PowerShell scripts, then sooner or later you are bound to end up creating a script that contains way too many "if-then" statements (although PowerShell's "if-then "statements are technically just "if" statements). While there does not seem to be any sort of practical limit to the number of if statements that you can include in a PowerShell script, excessive numbers of if statements can make the script difficult to read and even more difficult to debug.

One of the most effective ways to cut down on the clutter is to use a switch statement. A switch statement is similar to the case statement that is so often used in other programming languages. It's essentially just a structure that is designed to consolidate large numbers of "if" statements. Let's take a look at how a switch statement works.

To get started, here is a script containing a lot of "if" statements:

$Color = Read-Host 'Enter the name of a color'
If ($Color -eq 'Yellow'){Write-Host 'The color is ' $Color -ForegroundColor $Color}
If ($Color -eq 'Red'){Write-Host 'The color is ' $Color -ForegroundColor $Color}
If ($Color -eq 'Green'){Write-Host 'The color is ' $Color -ForegroundColor $Color}
If ($Color -eq 'Blue'){Write-Host 'The color is ' $Color -ForegroundColor $Color}
If ($Color -eq 'White'){Write-Host 'The color is ' $Color -ForegroundColor $Color}

This script prompts the user to enter the name of a color and then displays the words "the color is…" in the color that was entered. I will be the first to tell you that you could accomplish the same thing in a line or two of code without all of the "if" statements. Even so, I created this script, not because it is practical, but because it is easy to follow.

The script's first line prompts the user to enter the name of a color. The string of text that the user enters is then stored in a variable named $Color. From there, five different "if" statements test to see if the user entered a particular color name. If the color entered by the user happens to be yellow, red, green, blue or white then the color name is displayed in that color.

As previously mentioned, this script could easily be simplified to the point of being two lines of code. A simplified version might be:

$Color=Read-Host ‘Enter the name of a color' 
Write-Host ‘The color is ‘ $Color -ForegroundColor $Color

For the purposes of this article let's pretend that the script cannot be condensed as I just demonstrated and that all of the "if" statements contained in the script are absolutely necessary. Given those constraints, here is how you might simplify the script using a switch statement:

$Color=Read-Host ‘Enter the name of a color' 
Switch($Color)
{
‘Yellow' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color}
‘Red' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color}
‘Green' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color}
‘Blue' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color}
‘White' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color}
}

The first line of code is the same as what we had earlier. It uses the Read-Host cmdlet to prompt the user to enter a color name and then saves that color name to the $Color variable.

The second line of code is Switch($Color). This line of code tells PowerShell that we want to examine the contents of the $Color variable and branch in several possible directions depending on the variable's value. In other words, Switch($Color) is functionally similar to (if $Color -eq ‘').

Next, the script contains all of the comparative lines of code. Notice that these lines do not contain "if" statements. The reason for this is that we have already told PowerShell that we are looking at the $Color variable and comparing its contents against several possible options. Hence, we only need to provide PowerShell with those options, which in this case is just a list of colors. The "then" portion of each comparison is enclosed in brackets.

Keep in mind that I wrote this script with simplicity in mind. In the real world, the "then" portion of each comparison could consist of a function call or perhaps a pipeline operation.

It is worth noting that if more than one condition within the switch ends up being a match then both will execute. For example, if you had two lines of code checking to see if the color is green and then the user enters "green" as a color then the user would receive two messages stating that the color is green.

You can get around this potential problem by appending a break statement to the end of each line. The break statement terminates the switch once the first match is found. That way, you don't end up with multiple matches. Here is what the script might look like with the break in place:

$Color=Read-Host ‘Enter the name of a color' 
Switch($Color)
{
‘Yellow' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Red' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Green' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Blue' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘White' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
}

Another possibility is that none of the conditions will match what the user enters. The user might, for example, type "pink" or "purple," or the user could even misspell "red." Because you can't always account for every situation, PowerShell allows you to assign a default action that is applied when no match is found. The script below contains a default option:

$Color=Read-Host ‘Enter the name of a color' 
Switch($Color)
{
‘Yellow' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Red' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Green' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘Blue' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
‘White' {Write-Host ‘The color is ‘ $Color -ForegroundColor $Color; Break}
Default {Write-Host ‘No match was found'}
}

As you can see, if the user enters an invalid color name then a message will be displayed indicating that no match was found.

About the Author

Brien Posey is a 22-time Microsoft MVP with decades of IT experience. As a freelance writer, Posey has written thousands of articles and contributed to several dozen books on a wide variety of IT topics. Prior to going freelance, Posey was a CIO for a national chain of hospitals and health care facilities. He has also served as a network administrator for some of the country's largest insurance companies and for the Department of Defense at Fort Knox. In addition to his continued work in IT, Posey has spent the last several years actively training as a commercial scientist-astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space. You can follow his spaceflight training on his Web site.

Featured

comments powered by Disqus

Subscribe on YouTube