Windows复制命令返回代码?

ny6fqffe  于 6个月前  发布在  Windows
关注(0)|答案(5)|浏览(85)

我想在批处理文件中测试复制的成功/失败,但我找不到任何关于返回错误级别代码的文档。

copy x y
if %errorlevel%. equ 1. (
    echo Copy x y failed due to ...
    exit /B
) else (
  if %errorlevel% equ 2. (
      echo Copy x y failed due to ...
      exit /B
   )
... etc ...
)

字符串

xxe27gdn

xxe27gdn1#

在这种情况下,我会选择xcopy,因为错误级别已经记录在案(参见xcopy documentation,如下所述):

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都是一个更强大的解决方案。copyequivalent documentation没有记录错误级别。
顺便说一句,你可能需要重新考虑%errorlevel% * 变量的使用。* 它会产生意想不到的结果,至少在某些版本的Windows中,如果有人明确地做了一些愚蠢的事情,比如:

set errorlevel=22


在这些情况下,将使用实际的 * 变量 *,而不是获取实际的错误水平。“正常”的方法是(按降序排列,因为errorlevel是“大于或等于”检查):

if errorlevel 2 (
    echo Copy x y failed due to reason 2
    exit /B

)
if errorlevel 1 (
    echo Copy x y failed due to reason 1
    exit /B
)


此外,如果您运行的是Win7或Win Server 2008或更高版本,则应该考虑Robocopy,它现在是首选的批量复制解决方案。

9w11ddsr

9w11ddsr2#

还值得指出的是,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

字符串

c2e8gylq

c2e8gylq3#

我相信Copy只返回0表示成功,1表示失败。
XCopy记录了返回代码:
0 =文件复制无误。
1 =未找到要复制的文件。
2 =用户按CTRL+C终止xcopy。
4 =出现错误。内存或磁盘空间不足,或者您在命令行中输入了无效的驱动器名或无效的语法。
5 =发生磁盘写入错误。

zqry0prt

zqry0prt4#

还有一点我想强调:xcopyrobocopy只能复制文件,但不能重命名文件。
在查看原始情况(copy x y,对我来说看起来像重命名)时,我的印象是copy命令仍然是唯一适合此目的的命令。

relj7zay

relj7zay5#

Error# Description 
0 No error 
1 Not owner 
2 No such file or directory 
3 Interrupted system call 
4 I/O error 
5 Bad file number 
6 No more processes 
7 Not enough core memory 
8 Permission denied 
9 Bad address 
10 File exists 
11 No such device 
12 Not a directory 
13 Is a directory 
14 File table overflow 
15 Too many open files 
16 File too large 
17 No space left on device 
18 Directory not empty 
999 Unmapped error (ABL default)

字符串

相关问题