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

时间:2017-04-18 05:45:17

标签: windows batch-file cmd 7zip

我在文件夹中有大约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%\7-Zip\7z.exe" a "C:\ARCHIVE_%TDate%.zip" %%i
 del /a /f %%i
) 

请告知如何让它更快地运作。

1 个答案:

答案 0 :(得分:5)

除了使用非常慢的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%\7-Zip\7z.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