XCOPY覆盖操作



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

xcopy "C:UsersmeDocumentsApplyPatchBat" "C:UsersmeDesktopTest" /S/E/K 

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

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

xcopy本身不能预先备份,但有了xcopy的输出和一点for loop魔术,你就可以实现

@echo off
setlocal ENABLEDELAYEDEXPANSION
set source="C:UsersmeDocumentsApplyPatchBat"
set target="C:UsersmeDesktopTest"
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 %%~dpfbackup* md %%~dpfbackup
            rem only backup if not already backed up
            if not exist %%~dpfbackup%%~nxf move %%f %%~dpfbackup
        )
    )
)
xcopy %source% %target% /y /c /q /s /k

最新更新