如何编写仅在 xcopy 复制某些内容(退出代码 0)时才执行某些操作的条件语句

How to write conditional statement that does something only if xcopy copies something (exit code 0)

我想为 xcopy 创建一个条件语句,它只在 xcopy 复制某些东西时才做某事。

所以基本上我的意思是,如果 xcopy 复制一个文件,做一些事情。

如果不行,做点别的。

这是如何使用批处理完成的?

到目前为止我有以下内容:

xcopy "Z:\TestFiles.zip" "C:\Test\" /d /y

if xcopy exit code 0 (

)else

更新:

当运行以下脚本时:

xcopy /d /y "Z:\TestFiles.zip" "C:\Testing\"

echo %errorlevel%

以下是我得到的结果:

1 File(s) copied

C:\Users\jmills\Desktop>echo 0

0

_

0 File(s) copied

C:\Users\jmills\Desktop>echo 0

0

因为两个错误码出来都是0我不能用:

IF ERRORLEVEL 1 GOTO FilesCopied
IF ERRORLEVEL 0 GOTO NoFiledCopied

:NoFiledCopied
REM do something
GOTO eof

:FilesCopied
REM  do something
GOTO eof

:eof

您可以使用 robocopy 而不是 xcopy:

ROBOCOPY "Z:\" "C:\Test\" "TestFiles.zip"
IF ERRORLEVEL 1 GOTO FilesCopied
IF ERRORLEVEL 0 GOTO NoFiledCopied

:NoFiledCopied
REM do something
GOTO eof

:FilesCopied
REM  do something
GOTO eof

:eof

有关 robocopy 的更多信息: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

您可以使用 conditional execution operators && and ||:

xcopy /D /Y "Z:\TestFiles.zip" "C:\Test\" && echo success. || echo Failure!

或者,您可以检查 ErrorLevel 值:

xcopy /D /Y "Z:\TestFiles.zip" "C:\Test\"
rem // The following consition means 'if ErrorLevel is greater than or equal to 1':
if ErrorLevel 1 (
    echo Failure!
) else (
    echo Success.
)

之所以有效,是因为 xcopy 不是 return 负 ErrorLevel 值。


或者你可以查询%ErrorLevel%variable的值:

xcopy /D /Y "Z:\TestFiles.zip" "C:\Test\"
if %ErrorLevel% equ 0 (
    echo Success.
) else (
    echo Failure!
)

请注意,如果上述代码位于(带括号的)代码块中,您需要启用并应用 delayed variable expansion 以获取最新的 !ErrorLevel! 值。


根据您的 update, you want to detect whether or not xcopy copied any files. As per this related Super User thread, xcopy never returns an exit code of 1 (which I consider a design flaw), contrary to the documentation,即使使用了 /D 选项并且没有文件被复制。

为了避免这种情况,您可以通过 for /F loop 捕获 returned 摘要消息 (# File(s)),提取数字 (#) 并检查它是否是大于 0。尽管可能会出现其他异常,但仍应检查退出代码:

rem // Initialise variable:
set "NUM=0"
rem /* Use a `for /F` loop to capture the output of `xcopy` line by line;
rem    the first token is stored in a variable, which is overwritten in
rem    each loop iteration, so it finally holds the last token, which is
ewm    nothing but the number of copied files; if `xcopy` fails, number `0`
rem    is echoed, which is then captured as well: */
for /F "tokens=1" %%E in ('
    2^> nul xcopy /D /Y "Z:\TestFiles.zip" "C:\Test\" ^|^| echo 0
') do (
    rem // Capture first token of a captured line:
    set "NUM=%%E"
)
rem // Compare the finally retrieved count of copied files:
if %NUM% gtr 0 (
    echo Success.
) else (
    echo Failure!
)

考虑到捕获的摘要行是语言相关的,因此要提取的标记以及回显的失败文本 (0) 可能需要相应地进行调整。