Copying only newer files from one folder to another
Use XCOPY with /D and /L options, "copying" from folder 1 to folder 2.
The /D option restricts the copy to only new or modified files.
The /L option causes the command to list the files that would be copied, but prevents any copies from actually being made.
Then use FOR /F to process those results and actually copy the files to folder 3.
for /f "eol=: delims=" %F in ('xcopy /dl "folder1\*" "folder2"') do @copy "%F" "f3" >nul
If put in a batch file, then all %
must be doubled as %%
.
The XCOPY also prints out a summary of how many files are (would be) affected. The above will attempt to copy a file with the summary count "name", and of course fail. The redirection of output to nul prevents the error message from displaying. I tested on Windows 7 and was surprised the error message was on stdout and not stderr. If the error message on other versions is appearing on stderr, then the command should also get 2>nul to prevent the error message.
But there is a risk in hiding the error messages - what if a copy fails for some reason?
Here is a script that will list all files that were successfully copied, as well as indicate which (if any) failed. It uses FINDSTR to filter out the unwanted file count. It assumes the file count is in English, with the form NNN File(s)
, so it would have to be modified for other languages.
@echo off
for /f "eol=: delims=" %%F in (
'xcopy /dl "folder1\*" "folder2" ^| findstr /v "^[0-9][0-9]* File(s)"'
) do copy "%%F" "folder3" >nul && echo "%%F"|| echo FAILED: "%%f"
Here is a more complex variant that works with any language. It saves each file name to a variable and delays the copy until the next loop iteration. The last entry (the count) never gets copied.
@echo off
setlocal disableDelayedExpansion
set "file="
for /f "eol=: delims=" %%F in ('xcopy /dl "folder1\*" "folder2"') do (
if defined file (
setlocal enableDelayedExpansion
copy "!file!" "folder3" >nul && echo "!file!" || echo FAILED: "!file!"
endlocal
)
set "file=%%F"
)
I like ROBOCOPY instead. Used XCOPY for years then found a need for a restartable copy operation over a slow/twitchy internet connection.
ROBOCOPY src dest /s /e /xo
or mirror
ROBOCOPY src dest /mir
Use the Logging options to get your list for examination later.
ROBOCOPY src dest /s /e /xo /log:file