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

前端 未结 6 969
天涯浪人
天涯浪人 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 19:03

    The %ERRORLEVEL% variable doesn't get updated before the piped command is run; you have to use a wrapper as advised in the other answers.

    However, you can use "IF ERRORLEVEL #". For example:

    (
    type filename
    @REM Use an existing (or not) filename to test each branch
    IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OKAY)
    ) > logfile.txt
    

    The ECHO will only run if an error was returned; however %ERRORLEVEL% seems inconsistent.

    Edit: Changed example to be runnable as-is.

提交回复
热议问题