How do I get the error level of commands in a pipe in Windows batch programming?

mkl picture mkl · May 18, 2009 · Viewed 24.8k times · Source

Batch files return the error code of the last command by default.

Is it somehow possible to return the error code of a former command. Most notably, is it possible to return the error code of a command in a pipe?

For example, this one-line batch script

foo.exe

returns the error code of foo. But this one:

foo.exe | tee output.txt

always returns the exit code of tee, which is zero.

Answer

Nick Collier picture Nick Collier · Oct 5, 2014

I had a similar problem and settled on the following solution as I did not need to detect the exact error code just success or failure.

echo > .failed.tmp    

( foo.exe && del .failed.tmp ) | tee foo.log

if exist .failed.tmp (
    del .failed.tmp
    exit /b 1
) else (
    exit /b 0
)