Windows – How to get the error level of commands in a pipe in Windows batch programming


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


returns the error code of foo. But this one:

foo.exe | tee output.txt

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

Best Solution

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