2014-10-09 130 views
0

在bat文件我有一个简单的命令,如:XCOPY覆盖操作?

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

这没有工作在那里将复制所有包括子文件夹内的文件的文件。我知道你可以添加/ y使它自动覆盖。
如果我们想要创建一个语句,如果我们正在复制的这个文件存在于目标文件夹中,请将目标文件夹中的文件复制到备份文件夹中。

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

+1

不能在XCOPY做 - 你可以使用脚本来在xcopy运行之前检查并移动文件。 – foxidrive 2014-10-09 08:25:58

+0

如果你想跟踪版本 – 2014-10-09 08:38:20

回答

2

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 
+0

,你应该更好地使用[VCS](http://en.wikipedia.org/wiki/List_of_revision_control_software)。这是令人惊叹的,比我想要做的更优化。只有几个问题才能完全理解它。首先,支架中的xcopy是否实际上复制文件?所以%%一个将文件? %% b会是什么?最后一个问题,x!文件是什么! neq x是什么意思?非常感谢你的帮助! – 2014-10-10 02:32:42

+0

第一个xcopy具有/ l标志,它只是列出没有复制的文件。令牌= 1,*将使%%成为源代码(尾随“ - ”空格破折号)和%% b目的地(带有前导空格)。 enabledelayedexpansion允许您使用!代替变量%,但使用!意味着值刷新。所以x!文件! equ x is ask - is!file!空白? – 2014-10-10 04:15:53

+0

谢谢你现在更清楚:)我知道那个温度变化!标志,但是声明中的2 x是什么意思? – 2014-10-10 06:42:18