Manage Large Conditional Statements with Switches

1. Problem

You want to find an easier or more compact way to represent a large ifelseifelse conditional statement.

2. Solution

Use PowerShell’s switch statement to more easily represent a large ifelseifelse conditional statement.

For example:

        $temperature = 20
 
        switch($temperature)
        {
           { $_ -lt 32 }   { "Below Freezing"; break }
           32              { "Exactly Freezing"; break }
           { $_ -le 50 }   { "Cold"; break }
           { $_ -le 70 }   { "Warm"; break }
           default         { "Hot" }
        }



3. Discussion

PowerShell’s switch statement lets you easily test its input against a large number of comparisons. The switch statement supports several options that allow you to configure how PowerShell compares the input against the conditions—such as with a wildcard, regular expression, or even arbitrary script block. Since scanning through the text in a file is such a common task, PowerShell’s switch statement supports that directly. These additions make PowerShell switch statements a great deal more powerful than those in C and C++.

Although used as a way to express large conditional statements more cleanly, a switch statement operates much like a large sequence of if statements, as opposed to a large sequence of ifelseifelseifelse statements. Given the input that you provide, PowerShell evaluates that input against each of the comparisons in the switch statement. If the comparison evaluates to true, PowerShell then executes the script block that follows it. Unless that script block contains a break statement, PowerShell continues to evaluate the following comparisons.

Tags: , , , , , , , , , ,