in the bat file I got a simply command like :
xcopy "C:\Users\me\Documents\ApplyPatchBat" "C:\Users\me\Desktop\Test\" /S/E/K
This does the job where it will copy all the files including files inside subfolders. I know you can add /y to make it auto overwrite.
How ever I want to create an statement if this file that we are copying exist in the destination folder, copy the one in destination folder to a backup folder.
I wonder there is any IF statement I can add to after the command to detect if the file is existing? Or maybe an error level check when its asking do I want to overwrite?
P.S. This is for applying new patches to a program, where there are many layers of folders, that's why I use the /S/E/K in xcopy.
xcopy itself can't backup beforehand, but with output from xcopy and a bit of for loop magic you can make this happen
@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