【问题标题】:XCOPY overwrite action?XCOPY 覆盖操作?
【发布时间】:2014-12-04 02:15:14
【问题描述】:

在 bat 文件中,我得到了一个简单的命令,例如:

xcopy "C:\Users\me\Documents\ApplyPatchBat" "C:\Users\me\Desktop\Test\" /S/E/K 

这会复制所有文件,包括子文件夹中的文件。我知道您可以添加 /y 使其自动覆盖。
如果我们正在复制的这个文件存在于目标文件夹中,我想创建一个语句,将目标文件夹中的文件复制到备份文件夹中。

我想知道在命令之后我可以添加任何 IF 语句来检测文件是否存在?或者在询问我是否要覆盖时进行错误级别检查?
附言这是为了将新补丁应用到程序中,其中有很多层文件夹,这就是我在 xcopy 中使用 /S/E/K 的原因。

【问题讨论】:

  • 这不能在 xcopy 中完成 - 您可以在 xcopy 运行之前使用脚本检查和移动文件。
  • 如果您想跟踪修订,最好使用VCS

标签: batch-file cmd xcopy


【解决方案1】:

xcopy 本身无法预先备份,但是通过 xcopy 的输出和一些 for 循环魔法,您可以做到这一点

@echo off
setlocal ENABLEDELAYEDEXPANSION
set source="C:\Users\me\Documents\ApplyPatchBat"
set target="C:\Users\me\Desktop\Test\"

rem /l = list only, /u = already existing, /y = yes to replace
rem /f = display full source and destination file names, /c = continue on errors
rem /s = subdirectories, /k = keep attributes
rem split the strings at ->, we're only interested in the part after ->
for /f "usebackq tokens=1,* delims=>" %%a in (`xcopy %source% %target% /l /u /y /f /c /s /k`) do (
    set file=%%b
    rem ignore lines without a destination, e.g. 15 file(s) copied
    if x!file! neq x (
        rem remove the leading space, original string is source -> destination
        set file=!file:~1!
        for %%f in ("!file!") do (
            if not exist %%~dpf\backup\* md %%~dpf\backup
            rem only backup if not already backed up
            if not exist %%~dpf\backup\%%~nxf move %%f %%~dpf\backup
        )
    )
)
xcopy %source% %target% /y /c /q /s /k

【讨论】:

  • 这太棒了,比我想要做的优化了很多。只需几个问题即可完全理解它。首先,括号内的 xcopy 是否实际上复制了文件?所以 %%a 将是文件吗? %%b 会是什么?最后一个问题,什么是 x!file! neq x 是什么意思?非常感谢您的帮助!
  • 第一个 xcopy 有 /l 标志,它只列出文件而不复制。 tokens=1,* 将使 %%a 成为源(带有尾随“-”空格破折号)和 %%b 目标(带有前导空格)。 enabledelayedexpansion 允许您使用!代替 % 变量,但使用 !表示值刷新。所以x!文件! equ x 在问 - 是 !file!空白?
  • 谢谢,现在更清楚了 :) 我知道 temp var !符号,但语句周围的 2 x 是什么意思?
  • 这可能有助于为您解释这部分:robvanderwoude.com/variableexpansion.php
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 2014-11-19
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多