Returning an errorlevel from WSH VBScripts
Sunday, June 3, 2007 8:32:29 PM
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()
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.