Why use Switch?

In PowerShell you can use an if statement to compare things and determine actions based upon the result. You also can use elseif to keep comparing values until you reach a desired (or not so desired) result.

Switch allows you to take a variable you define, and then based upon its value perform different actions.


In this example I will show you a switch statement I used in a script that uses the Weather Underground API to send HTML emails detailing your requested weather forecast. Consider this a teaser until I post that script itself.

What I wanted to do

In this example I wanted to take a returned percentage, and then change a variable to display the appropriate text result. It compares the returned value of the hour's chance of precipitation set in $hourPrecip, and then based on that number changes the variable $popText accordingly.

The Code

Switch ($hourPrecip) {
                        {$_ -lt 20} {
                            $popText = 'No mention'
                        {$_ -eq 20} {
                            $popText = 'Slight Chance'
                        {($_ -lt 50 -and $_ -gt 20)} {
                            $popText = 'Chance'
                        {$_ -eq 50} {
                            $popText = 'Good chance'
                        {($_ -lt 70 -and $_ -gt 50)} {
                            $popText = 'Likely'
                        {$_ -ge 70} {
                            $popText = 'Extremely likely'

So now you display the percentage, as well as its correlating text value which describes what the percentage means.

If the value was 51 for $hourPrecip, then $popText will be set to Likely

The Weather Underground post will be coming soon!

Do you use switches in your scripts, and if so, how do you like to use them?