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

标签 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
) 

请指教如何让它工作得更快。

最佳答案

除了使用非常慢的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

关于windows - 使用 7ZIP 和 CMD 压缩和删除超过 7 天的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464474/

相关文章:

java - System.exit(int code) 和 Runtime.getRuntime().exit(int code) 的区别

windows - 如何使用 Windows 命令行将 12 小时格式的时间添加到文件名?

windows - 批量字符转义

c# - 使用 C# Windows 窗体远程关闭 PC?

cmd - 如何在 NET USER 命令中查看完整的组名

windows - 在 Windows 上递归删除所有 .svn 目录的命令

windows - 当我将我的 Perl 程序从 Linux 移至 Windows 时,为什么日期和数字格式会发生变化?

windows - 我可以在同一台服务器上运行 Xampp 和 tomcat 吗

windows - 调用套接字绑定(bind)导致 Windows 蓝屏

batch-file - 从多个 TXT 文件中删除标题行的命令行脚本