Question

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?

Was it helpful?

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

OTHER TIPS

You can define a variable to function as a simple "macro". Saves a lot of typing, and doesn't look bad either.

@echo off
setlocal
set "copy=if errorlevel 1 (goto :error) else copy"
set "xcopy=if errorlevel 1 (goto :error) else xcopy"

%copy% "somepath\file1" "location"
%copy% "somepath\file2" "location"
%xcopy% /s "sourcePath\*" "location2"
rem etc.
exit /b

:error
rem Handle your error

EDIT

Here is a more generic macro version that should work with any commmand. Note that a macro solution is significantly faster than using CALL.

@echo off
setlocal
set "ifNoErr=if errorlevel 1 (goto :error) else "

%ifNoErr% copy "somepath\file1" "location"
%ifNoErr% copy "somepath\file2" "location"
%ifNoErr% xcopy /s "sourcePath\*" "location2"
rem etc.
exit /b

:error
rem Handle your error
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top