Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
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:
Case 99 Wscript.Echo
"An error has occurred.
"
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
Send us your feedback | « Previous | Next » |