How do I get the application exit code from a Windows command line?

I am running a program and want to see what its return code is (since it returns different codes based on different errors).

I know in Bash I can do this by running

echo $?

What do I do when using cmd.exe on Windows?


A pseudo environment variable named errorlevel stores the exit code:

echo Exit Code is %errorlevel%

Also, the if command has a special syntax:

if errorlevel

See if /? for details.

Example

@echo off
my_nify_exe.exe
if errorlevel 1 (
   echo Failure Reason Given is %errorlevel%
   exit /b %errorlevel%
)

Warning: If you set an environment variable name errorlevel , %errorlevel% will return that value and not the exit code. Use (set errorlevel= ) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.


Testing ErrorLevel works for console applications, but as hinted at by dmihailescu , this won't work if you're trying to run a windowed application (eg Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel .

start /wait something.exe
echo %errorlevel%

Use the built-in ERRORLEVEL Variable:

echo %ERRORLEVEL%

But beware if an application has defined an environment variable named ERRORLEVEL!

链接地址: http://www.djcxy.com/p/55944.html

上一篇: 如何从批处理文件中检查文件是否存在

下一篇: 如何从Windows命令行获取应用程序退出代码?