Export (0) Print
Expand All

Select Case

Microsoft® Windows® 2000 Scripting Guide

The Select Case statement provides a more readable alternative to the If Then ElseIf statement. If you have a script that evaluates more than three conditions, you will typically find it faster and easier to use Select Case rather than If Then ElseIf. For example, the following code sample uses the Select Case statement to evaluate the printer status codes that can be returned by using WMI:



Select Case PrinterStatus
    Case 1 strCurrentState = "Other"
    Case 2 strCurrentState = "Unknown"
    Case 3 strCurrentState = "Idle"
    Case 4 strCurrentState = "Printing"
    Case 5 strCurrentState = "Warming Up"
End Select

By comparison, the task written using an If Then ElseIf statement is almost twice as long, and more difficult to read:



If PrinterStatus = 1 Then
    strCurrentState = "Other"
ElseIf PrinterStatus = 2 Then
    strCurrentState = "Unknown"
ElseIf PrinterStatus = 3 Then
    strCurrentState = "Idle"
ElseIf PrinterStatus = 4 Then
    strCurrentState = "Printing"
ElseIf PrinterStatus = 5 Then
    strCurrentState = "Warming Up"
End Select

To use a Select Case statement, do the following:

  1. Start the statement block with Select Case, followed by the name of the variable being evaluated.

  2. For each potential value, use a Case statement followed by the potential value, and then by any code that should be run if the statement is true. For example, if you want to echo an error message if the value is equal to 99, use a code statement similar to the following:

    
    
    Case 99 Wscript.Echo "An error has occurred."
    
    
  3. Close the statement block with End Select.

You can also use a Case Else statement to account for all other possibilities:



Select Case PrinterStatus
    Case 1 strCurrentState = "Other"
    Case 2 strCurrentState = "Unknown"
    Case 3 strCurrentState = "Idle"
    Case 4 strCurrentState = "Printing"
    Case 5 strCurrentState = "Warming Up"
    Case Else strCurrentState = "Status cannot be determined."
End Select

In addition, you can place the Case statement on one line, followed by the lines of code that should be run if the statement is True. For example:



Case 1
    strCurrentState = "Other"
    Wscript.Echo strCurrentState
Case 2

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft