使用 7ZIP 和 CMD 压缩和删除超过 7 天的文件

ZIP and delete files older than 7 days using 7ZIP and CMD

我的文件夹中有大约 20 000 个文件,我想压缩和删除超过 7 天的文件。我试过这个脚本,但它运行得很慢:

Set TDate=%date:~6,4%%date:~3,2%%date:~0,2%

for /f "delims=" %%i in ('
 forfiles /p C:\ARCHIVE /s /m *.txt /d -7 /c "cmd /c echo @path"
') do (
 "%ProgramFiles%-Zipz.exe" a "C:\ARCHIVE_%TDate%.zip" %%i
 del /a /f %%i
) 

请告知如何让它运行得更快。

除了使用 forfiles 非常慢(但我认为对于这个脚本来说这是不可避免的)之外,脚本的主要减速部分是在每次循环迭代中对存档的修改。相反,您应该只进行一次归档,也许使用列表文件,然后让归档工具自行删除成功压缩的文件:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=C:\ARCHIVE"
set "_PATTERN=*.txt"
set "_LIST=%TEMP%\%~n0.tmp"
set "_ARCHIVER=%ProgramFiles%-Zipz.exe"

rem // Get current date in locale-independent format:
for /F "tokens=2 delims==" %%D in ('wmic OS get LocalDateTime /VALUE') do set "TDATE=%%D"
set "TDATE=%TDATE:~,8%"

rem // Create a list file containing all files to move to the archive:
> "%_LIST%" (
    for /F "delims=" %%F in ('
        forfiles /S /P "%_ROOT%" /M "%_PATTERN%" /D -7 /C "cmd /C echo @path"
    ') do echo(%%~F
) && (
    rem // Archive all listed files at once and delete the processed files finally:
    "%_ARCHIVER%" a -sdel "%_ROOT%_%TDATE%.zip" @"%_LIST%"
    rem // Delete the list file:
    del "%_LIST%"
)

endlocal
exit /B