Set errorlevel in Windows batch file

后端 未结 4 948
情书的邮戳
情书的邮戳 2021-02-04 04:47

I am writing a batch script that will loop through each line of a text file, (each line containing a filename) check if the file exists and then runs the file and moves it.

4条回答
  •  我在风中等你
    2021-02-04 05:14

    Use something like the following subroutine:

    :return
       ECHO @exit /b %1 >ret.cmd
       CALL ret.cmd
       GOTO :eof
    

    Then use it like this:

    :Attempt
       SETLOCAL
       CALL somethingThatFails
       SET retcode=!errorlevel!
       CALL somethingThatPasses : don't care about the errorlevel here
       CALL :return !retcode!
       ENDLOCAL
       CALL :eof
    

    So, the whole thing would looke something like:

    test.cmd...

    @ECHO OFF
    
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    CALL :Attempt
    IF !errorlevel! NEQ 0 (ECHO Attempt Failed) ELSE (ECHO Attempt succeeded!)
    GOTO :eof
    
    :Attempt
       SETLOCAL
       CALL somethingThatFails
       SET retcode=!errorlevel!
       CALL somethingThatPasses : don't care about the errorlevel here
       CALL :return %retcode%
       ENDLOCAL
       CALL :eof
    
    :return
       ECHO @exit /b %1 >return.cmd
       CALL ret.bat
       GOTO :eof
    

    somethingthatfails.cmd...

    DIR some command that fails >nul 2>&1
    

    somethingthatpasses.cmd...

    DIR >nul 2>&1
    

    The one side effect of this is a file laying around called ret.cmd. I usually use an :end subroutine that does cleanup and would delete it.

提交回复
热议问题