2012-02-14 39 views
2

我有一個批處理文件,只是做一個副本和xcopy命令的負載,如果他們中的任何一個失敗我需要跳出複製到一個goto標籤,但這將是非常不方便必須在每個副本之後檢查錯誤級別。Windows批處理文件所有包含錯誤級別

我懷疑它可能是不可能的,但是有沒有辦法讓我可以做一大塊copys/xcopys並檢查錯誤級別是否超過零?

回答

1

您可以將操作包裝在子程序中;

@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 
+0

多數民衆贊成在輝煌,謝謝=) – 2012-02-14 16:01:45

+1

應該工作,但爲什麼延期擴張?如果任何路徑包含'!',則延遲擴展將導致問題。另外爲什麼不在IF語句中設置waserror並消除goto:失敗? – dbenham 2012-02-14 16:18:20

2

您可以定義一個變量作爲一個簡單的「宏」。節省了大量的打字工作,而且看起來也不錯。

@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 

編輯

這裏是一個更通用的宏版本應該與任何條命令工作。請注意,宏解決方案比使用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 
相關問題