Select Case


Definition: Executes one of several groups of statements, depending on the value of an expression.

 

In VBScript you can test for multiple possibilities by using a long and sometimes-complicated series of If Then ElseIfstatements. Alternatively, you can achieve the same effect – with far less typing – by using a Select Case statement.

 

In Windows PowerShell you can emulate (and, in some ways, improve upon) the Select Case statement by using the Switchstatement. To explain how the Switch statement works, let’s take a look at some sample code:

 

$a = 5

switch ($a)
    {
        1 {"The color is red."}
        2 {"The color is blue."}
        3 {"The color is green."}
        4 {"The color is yellow."}
        5 {"The color is orange."}
        6 {"The color is purple."}
        7 {"The color is pink."}
        8 {"The color is brown."}
        default {"The color could not be determined."}
    }

 

In the preceding code we assign the value 5 to the variable $a. We then create a Switch block that assesses the value of $ a andtakes the appropriate action based upon that value:

 

switch ($a)

 

As you can see, all we have to do is insert the Switch keyword followed by the value to be tested (which must be enclosed in parentheses).

 

Next we list the possible values for $a along with the corresponding action (this entire block, incidentally, must be enclosed in curly braces). For example, if $ a isequal to 1 we want to echo back a message saying that the color is red. Therefore, we use this line of code, with the action to be taken enclosed in curly braces:

 

1 {"The color is red."}

 

See how that works? (It’s actually pretty easy.) We can also specify an action to be taken if none of the preceding Case statements are true (the same thing you do with Case Else in VBScript). To do that we simply use the defaultcondition followed by the desired action:

 

default {"The color could not be determined."}