我有一个batch file,只是做一个副本和xcopy命令的负载,如果其中任何一个失败,我需要跳出复制到一个goto标签,但这将是非常不方便,每个副本后检查错误级别。
我怀疑这可能是不可能的,但是有没有办法可以做一大堆copys / xcopys,并检查错误级别是否超过了零?
你可以把这个动作包装在一个子程序中。
@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
你可以定义一个变量来作为一个简单的“宏”。 节省了很多打字,而且看起来也不错。
@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