Hello, this is an old post, I know
But I was looking for a solution doing with Xcopy what I normally do with the
Robocopy /mir command. I had to since the ICT-guys at my work blocked Robocopy.
So, there are a couple of good suggestions here but I missed the
selective deletion of extra files in a directory-tree as I don't like deleting and rewriting
all files on my USB-stick.
So I came up with the following solution, using FOR, Xcopy and DEL to
delete the extra files in the
destination first and the
Xcopying the
newer files from the source to the destination
if you want.
For detailed information see:
Xcopy at Microsoft docs.
Simply copy the code below in Notepad and save it as: MirrorTo.cmd
Note: This example batch will not stop after you pressed the key to continue!
Code: Select all
@ECHO off
rem Syntaxis: MirrorTo.cmd <source> <destination>
CLS
ECHO Given Commandline: %~nx0 %*
rem - Set variables, including a quick check on the last two lines.
rem Note: Using the ~ character here removes any qoutes from long filenames.
SET str_SrcePath=%~1
SET str_TrgtPath=%~2
ECHO * Mirror the following directorys to each other.
ECHO Source : "%str_SrcePath%"
ECHO Destination : "%str_TrgtPath%"
IF "%str_TrgtPath%"=="" ECHO *** ERROR *** No destination directory given!&EXIT /b 3
IF not exist "%str_SrcePath%\*.*" ECHO *** ERROR *** Source: '%1' is NOT a directory!&EXIT /b 3
ECHO Press any key to continue, Ctrl+C to quit.
PAUSE > NUL
ECHO.
ECHO - Copy ONLY newer files from destination to the source.
rem Note: If you DON'T want this simply remove this line OR replace /y with /-y (the /-y option will prompt you to confirm overwriting an existing file, you can also use this for testing).
Xcopy "%str_TrgtPath%" "%str_SrcePath%" /d /u /r /v /y /h /i /s
ECHO.
ECHO - Delete ONLY extra files from destination.
rem Note: You can replace 'DEL /q' with 'DEL /p' for testing.
FOR /f "delims=*" %%F in ('Xcopy "%str_TrgtPath%" "%str_SrcePath%" /d /r /v /y /h /i /s /l') DO IF exist "%%~F" (DEL /q /f "%%~F") ELSE (ECHO %%F deleted.)
ECHO.
ECHO - Now copy only newer AND non-existing files from source to destination.
Xcopy "%str_SrcePath%" "%str_TrgtPath%" /d /r /v /y /h /i /s
rem - Finally remove the previously created variables.
SET str_SrcePath=
SET str_TrgtPath=
EXIT /b 0
You can customize this code using options like Xcopy ... /l, then pause first etcetera but that will be to much here I guess.
I hope this is usable for more people, good luck!