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

前端 未结 6 959
天涯浪人
天涯浪人 2021-01-03 18:22

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 t

6条回答
  •  旧巷少年郎
    2021-01-03 18:43

    After about one day of digging, I found a way to do that:

    set error_=0
    9>&1 1>&2 2>&9 (for /f "delims=" %%i in ('9^>^&1 1^>^&2 2^>^&9 ^(^(^(2^>^&1 call "%homeDir%%1"^) ^|^| ^(1^>^&2 2^>nul echo FAILED^)^) ^| 2^>nul "%homeDir%mtee" /T /+ "%homeDir%logs\%date_%_%1.log"^)') do (set error_=1))
    
    exit /b %error_%
    

    In the example above "%homeDir%%1" is being executed and its output is piped to "%homeDir%mtee". This line detects failures (I'd suggest you to draw a diagram of batch contexts and their stdin/stdout/stderr assignments in order to understand what it does :-) ). I did not find a good way to extract the actual errorlevel. The best thing I got was to replace the 'echo' command with some batch script call 'call rc.bat' which look like:

    @echo %errorlevel%
    

    and then replace 'set error_=1' with 'set error_=%%i'.

    But the problem is that this call may fail too, and it is not easy to detect that. Still, it is much better than nothing -- I did not find any solution for that on the Internet.

提交回复
热议问题