1

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"
DextrousDave
  • 405
  • 6
  • 12
  • 24

1 Answers1

2

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

and31415
  • 14,610