我想testing一个batch file中副本的成功/失败,但是我找不到任何有关返回错误代码的文档。 例如
copy xy if %errorlevel%. equ 1. ( echo Copy xy failed due to ... exit /B ) else ( if %errorlevel% equ 2. ( echo Copy xy failed due to ... exit /B ) ... etc ... )
在这种情况下,我会选择xcopy
,因为错误级别是有记录的(请参阅下面的xcopy文档 ):
Exit code Description ==== =========== 0 Files were copied without error. 1 No files were found to copy. 2 The user pressed CTRL+C to terminate xcopy. 4 Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line. 5 Disk write error occurred.
无论如何, xcopy
是一个更为强大的解决方案。 copy
的等效文档不记录错误级别。
另外,您可能想重新考虑使用%errorlevel%
变量。 如果有人明确地做了一些愚蠢的事情,那就会产生令人讨厌的后果(至少在某些版本的Windows中):
set errorlevel=22
在这些情况下,实际的变量将被用来代替实际的错误级别。 这样做的“正常”方法是(按降序排列,因为errorlevel
是“大于或等于”检查):
if errorlevel 2 ( echo Copy xy failed due to reason 2 exit /B ) if errorlevel 1 ( echo Copy xy failed due to reason 1 exit /B )
如果您正在运行Win7或Win server 2008或更高版本,则应该查看Robocopy ,它现在是首选的大容量复制解决方案。
也许值得指出的是,xcopy并不总是返回你所期望的错误代码。
例如,当试图使用通配符复制多个文件但没有要复制的文件时,您希望返回错误代码1(“没有找到要复制的文件”),但实际上它返回0(“文件被复制而没有错误” )
C:\Users\wilson>mkdir bla C:\Users\wilson>mkdir blert C:\Users\wilson>xcopy bla\* blert\ 0 File(s) copied C:\Users\wilson>echo %ERRORLEVEL% 0
我相信Copy
只会返回0成功或1失败。
XCopy
记录了返回码:
0 =文件被复制没有错误。
1 =找不到要复制的文件。
2 =用户按下CTRL + C来终止xcopy。
4 =发生初始化错误。 没有足够的内存或磁盘空间,或者在命令行上输入了无效的驱动器名称或无效的语法。
5 =发生磁盘写入错误。
还有一点我要强调: xcopy
和robocopy
只能复制文件,但不能重命名。
在看原来的情况( copy xy
,看起来像是重命名给我的),我觉得copy
命令仍然是唯一适合这个目的的命令。