Select Case

Microsoft® Windows® 2000 Scripting Guide

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:

  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 

send us your feedback Send us your feedback « Previous | Next »   


Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 635

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net