Windows Batch file to copy latest files to a new folder
2014-04
I want to copy the latest file from a Folder and its subfolders to a new location.
The following code works well, BUT I do not want to filter by Date AND Time (/O:D), but DATE only, so that all latest files from the same date will be copied to the new location as the latest files.
FOR /F "delims=|" %%I IN ('DIR "D:\Backups\DB\*.bak" /B /O:D /S') DO SET NewestFile=%%I
copy "%NewestFile%" "D:\Backups\DB\Latest"
Solution
The following batch script makes use of the forfiles
command, which is not available by default in Windows XP. If that's the operating system you use, you'll have to manually download it. While the syntax is similar, it's not identical.
@echo off
REM set the working directory
pushd "D:\Backups\DB"
REM get the latest modified .bak file
for /f "delims=" %%G in ('dir *.bak /b /o:-d /s 2^>nul') do (
REM copy the newest files
call :copyNewest %%G "Latest"
REM restore the previous working directory
popd
goto:EOF
)
:copyNewest
setlocal
REM make sure there's something to copy
if "%~1" == "" exit /b
REM check output folder
if "%~2" == "" exit /b
REM get the file path
set filePath=%~dp1
REM strip the trailing backslash char
set filePath=%filePath:~0,-1%
REM copy latest files which share the same date
for /f "delims=" %%G in ('"forfiles /p "%filePath%" /m "%~nx1" /c "cmd /c echo @fdate""') do (
forfiles /p "%cd%" /m *.bak /s /c "cmd /c echo @relpath | findstr /i /c:"\%~2" >nul || copy @path "%cd%\%~2" >nul" /d %%G
)
endlocal & exit /b
My scanner software puts it's file into YYYY_MM_DD
subfolders in C:\Dokumente und Einstellungen\Enrico\Eigene Dateien\Eigene Bilder\MP Navigator EX
. The files are all JPEG files.
Now I need to copy them out of the virtual machine, into a shared drive which is called E:
.
I would like to copy the subfolders into the shared drive, so that I have those date folders there. If a new picture is added to today's folder, it should be copied as well.
On Linux, I would just use rsync -avE
for this.
How can I do this with a plain batch file in XP and 7?
You can use xcopy
to copy entire directories (including subdirectories).
The syntax is:
xcopy source destination /S
where the /S
switch includes non-empty directories (/E
copies empty directories as well).
There are a couple of switches that serve as a backup solution:
/M
copies only changed files (archive attribute set) and unsets the attribute./D
copies only those files whose source time is newer than the destination time.
Use Robocopy which is the microsoft equivalent to rsync.
To get the same result as rsync -avE /source /dest
use the following command:
robocopy source dest /e
To run rsync -avE --delete
you can directly use robocopy /mir
.