简体   繁体   中英

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

I have about 20 000 files in the folder, I want to zip and delete files older than 7 days. I tried this script, but it works very slow:

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
) 

Please advise how to make it work faster.

Besides usage of forfiles which is very slow (but inevitable for this script, I think), the main decelerating part of your script is the modification of the archive in every single loop iteration. Instead, you should do the archiving once only, perhaps using a list file, then let the archiving tool delete files it successfully compressed on its own:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM