Returning an errorlevel from WSH VBScripts
Sunday, 3. June 2007, 20:32:29
Most people complain that cscript.exe (Windows Scripting Host) always returns an errorlevel of 0 (zero) to its parent batch process after running WSH scripts, even when the script dies with a known Err.Number. Others complain that their calls to WScript.Quit Err.Number never get called because the script dies before the script gets a chance to call WScript.Quit. And using the horrid On Error Resume Next is simply out of the question here.
So what gives, is there a solution? YES!
The trick is using the information from my previous VBScript post, and strategically handling errors inside the VBScript Class_Terminate() event -- which is guaranteed to be called, even if your script dies during Class_Initialize()
For example:
As a result of saving-off any errors in the final Class_Terminate() event handler, you can adequately return the WSH error code to your parent batch command script for further processing, like so:
...and so forth.
As you can see, this is pretty simple, but most VBScript programmers simply aren't aware of the Class statement introduced in VBScript 5. As such, I rarely ever see it being used out in-the-wild; which is unfortunate.
Hope this helps. Enjoy.
So what gives, is there a solution? YES!
The trick is using the information from my previous VBScript post, and strategically handling errors inside the VBScript Class_Terminate() event -- which is guaranteed to be called, even if your script dies during Class_Initialize()
For example:
Option Explicit
Dim exitcode : exitcode = 0
Class Global
Private Sub Class_Initialize()
s = "" ' Generate an undefined variable error
End Sub
Private Sub Class_Terminate()
exitcode = Err.Number
End Sub
End Class
Dim Main : Set Main = New Global
Set Main = Nothing
WScript.Quit exitcode
As a result of saving-off any errors in the final Class_Terminate() event handler, you can adequately return the WSH error code to your parent batch command script for further processing, like so:
@echo off cscript.exe //NoLogo //E:VBScript test.vbs if errorlevel == 500 echo An undefined variable exists!
...and so forth.
As you can see, this is pretty simple, but most VBScript programmers simply aren't aware of the Class statement introduced in VBScript 5. As such, I rarely ever see it being used out in-the-wild; which is unfortunate.
Hope this helps. Enjoy.

