Search code examples
windowsbatch-filexcopyerrorlevel

Windows batch file all encompassing error levels


I have a batch file which just does a load of copy and xcopy commands, if any of them fail I need to jump out of the copying to a goto label, but it would be very inconvenient to have to check errorlevels after every single copy.

I suspect it may not be possible, but is there a way that I can do a huge block of copys/xcopys and check at the end whether the errorlevel ever went above zero?


Solution

  • You could wrap the action in a subroutine;

    @echo off
    setlocal enabledelayedexpansion
    set waserror=0
    
    call:copyIt "copy", "c:\xxx\aaa.fff",  "c:\zzz\"
    call:copyIt "xcopy /y", "c:\xxx\aaa.fff",  "c:\zzz\"
    call:copyIt "copy", "c:\xxx\aaa.fff",  "c:\zzz\"
    call:copyIt "copy", "c:\xxx\aaa.fff",  "c:\zzz\"
    
    goto:eof
    
    :copyIt
        if %waserror%==1 goto:eof 
        %~1 "%~2" "%~3"
        if !ERRORLEVEL! neq 0 goto:failed
        goto:eof
    
    :failed
       @echo.failed so aborting
       set waserror=1