Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
In general, VBScript processes each line of code in succession. Procedures are an exception to this rule. Neither subroutines nor functions are run unless they have been specifically invoked somewhere in the script. If a procedure has not been invoked, the procedure is simply skipped, regardless of where it appears within the script.
For example, the following script includes a subroutine embedded in the middle of the code. However, this subroutine is never actually called.
Wscript.Echo
"A
"Sub EchoLine2 Wscript.Echo
"B
"End Sub Wscript.Echo
"C
"
When the preceding script runs under CScript, the following output appears in the command window. Because the subroutine was never called, the subroutine and all the code inside it was skipped and not run:
A C
The flow of the script goes like this:
To ensure that a subroutine runs, it must be called. This is done using a statement that consists solely of the subroutine name. For example, the following script echoes the message "A", calls the subroutine named EchoLineB, and then echoes the message "C".
Wscript.Echo
"A
"EchoLine2 Wscript.Echo
"C
"Wscript.Quit Sub EchoLineB Wscript.Echo
"B
"End Sub
When the preceding script runs under CScript, the following output appears in the command window:
A B C
The flow of the script goes like this:
Procedures can be placed anywhere within a script, with no degradation of performance. However, the placement of procedures can affect the ease with which a script can be read and maintained. For more information about placing procedures within a script, see "Scripting Guidelines" in this book.
In the following script, an error-handling procedure is used to display any WMI errors that might occur. Throughout the script the Err object is checked. If the value is anything but 0, this means an error occurred; the ErrorHandler subroutine is called, and the appropriate error message is displayed.
On Error Resume Next Set objWMIService = GetObject(
"Winmgmts:root\cimv2
") If Err <> 0 Then ErrorHandler End If Set colPrinters = objWMIService.ExecQuery _ (
"SELECT * FROM Win32_Printer WHERE Name='TestPrinter'
") If Err <> 0 Then ErrorHandler End If For Each objPrinter in colPrinters Wscript.Echo objPrinter.Name Next Sub ErrorHandler Select Case Hex(Err.Number) Case
"80041001
"Wscript.Echo
"The call failed.
"Case
"80041002
"Wscript.Echo
"The object could not be found.
"Case
"80041010
"Wscript.Echo
"The specified class is not valid.
"Case
"8004103A
"Wscript.Echo
"The specified object path was invalid.
"Case
"80041048
"Wscript.Echo
"The specified class is not supported.
"Case Else Wscript.Echo
"An unknown error occurred.
"End Select Err.Clear End Sub
Send us your feedback | « Previous | Next » |