Run a Windows command program anywhere and return output code
What's a good practice to have a program called by an external scheduler and see all output and correctly return the exit code, regardless of what path it is run in (including UNC paths)?
Here's what I use. This example is for a vbscript program I looked at capturing the output and return code from:
PUSHD "%~dp0\" CALL cscript //nologo ..\scripts\nameofscript.wsf 2>&1 SET progerr=%errorlevel% POPD EXIT /B %progerr%
What's this doing?
- PUSHD is changing to a directory, and mapping a path if it's a network directory
- %~dp0 is a built in variable which is the full absolute path of where the batch file is located
- CALL is calling the program
- 2>&1 is redirecting the standard error stream (stderr) to standard out (stdout) so schedulers that only log output will also see errors (such as compile or runtime errors for the vbscript)
- SET progerr=%errorlevel% - this is storing the error code of the program in a variable so we can use it later
- POPD - this is reverting the change made by PUSHD (good practice!)
- EXIT /B %progerr% - this is forcing the batch script to exit with the same error code that we saved from the script
There's of course more than one way to do it (including using powershell instead), but this is a fairly stable way to do it the old fashioned way!