解决方案

解决方案

我想将文件夹及其子文件夹中的最新文件复制到新位置。

以下代码运行良好,但我不想按日期和时间(/O:D)进行过滤,而只按日期进行过滤,以便将同一日期的所有最新文件作为最新文件复制到新位置。

FOR /F "delims=|" %%I IN ('DIR "D:\Backups\DB\*.bak" /B /O:D /S') DO SET NewestFile=%%I
copy "%NewestFile%" "D:\Backups\DB\Latest"

答案1

解决方案

以下批处理脚本使用了该forfiles命令,该命令在 Windows XP 中默认不可用。如果您使用的操作系统是 Windows XP,则必须手动下载. 虽然语法类似,这并不完全相同

@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

相关内容