我想为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个文件
C:\ Users \ jmills \ Desktop> echo 0
0
_
0 文件已复制
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
答案 0 :(得分:2)
您可以使用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
不会返回负的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,您想检测xcopy
是否复制了任何文件。根据与此相关的Super User thread,xcopy
永远不会返回1
(我认为是设计缺陷)的退出代码,与documentation相反,即使{{1 }}选项,不会复制任何文件。
要避免这种情况,您可以用for /F
loop捕获返回的摘要消息(/D
),提取数字(# 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!
)
)。
答案 1 :(得分:0)
您可以使用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