Create console apps that return an exit code

Writing an application that returns an ERRORLEVEL to Dos is quite difficult in VB6, because you are forced to use a Windows API that ends the application immediately, thus preventing orderly release of resources. Conversely, this task is quite simple in VB.NET, thanks to the Exit static method of the Environment class.

' Terminate the current application and return ERRORLEVEL = 1Environment.Exit(1)

As with any regular command-line utility, you can test the errorlevel in a batch file as follows

@ECHO OFFREM call the app that can set the errorlevelMyAppREM higher errorlevels must be tested firstIF ERRORLEVEL 3 GOTO e3IF ERRORLEVEL 2 GOTO e2IF ERRORLEVEL 1 GOTO e1REM Add here code for Errorlevel = 0REM ...GOTO End:e1REM Add here code for Errorlevel = 1REM ...GOTO End:e2REM Add here code for Errorlevel = 2REM ...GOTO End:e3REM Add here code for Errorlevel = 3REM ...:End

UPDATE: Richard Deeming and Burton Rodman wrote us to point at an alternative, and much cleaner way, to have your VB app return an exit code to the operating system. You just have to create a Function named Main, which returns an Integer, as in:

Function Main() As Integer    ' ...    ' Return ERRORLEVEL = 1    Return 1End Function

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: