【问题标题】:Use 7-Zip to Compress folders within a directory and then delete the source folder used to create the .zip file使用 7-Zip 压缩目录中的文件夹,然后删除用于创建 .zip 文件的源文件夹
【发布时间】:2014-03-21 08:56:39
【问题描述】:

我需要运行一个脚本来压缩目录结构中的 2 级文件夹中的所有文件夹。我希望脚本压缩日志文件夹中的所有文件夹,然后删除原始文件夹,从而节省空间负载。为了说明我希望压缩的文件夹,请参见下文:

驱动器位置-->机器名-->logtype-->folders_i_want_to_compress

在文件夹 2 中有日期格式为 yyyymmdd 的文件夹,我希望将这些文件夹压缩为 zip 文件。

我不知道如何创建一个脚本来执行此操作,但我确实在这里找到了一个类似的脚本:7-Zip compress files within a folder then delete files

...看起来像这样:

REM Usage: ZipFilesRecursively.bat "C:\My Files"
for /R "%~f1" %%F in (*) do (
    7z a -mx9 "%%~dpnxF.7z" "%%F"
    if exist "%%~dpnxF.7z" del "%%F"
)

但这仅适用于文件。我无法解决如何更改它以使其适用于文件夹而不是文件,尽管我相信它的开始将与 /D 开关而不是 /R 一起使用。

由于文件夹的路径部分基于机器名称,因此我需要将其输入到脚本中,因此我计划使用来自另一个批处理文件的调用来运行压缩/删除脚本。

调用脚本如下所示

Call zipdeletetest4 machinename1
Call zipdeletetest4 machinename2    
Call zipdeletetest4 machinename3
Call zipdeletetest4 machinename4

有人可以帮忙吗?

【问题讨论】:

  • 我最终设法让压缩部分使用... for /d %%x in ("E:\location\machinename\Logs\*.*") do start "C:\Program Files (x86)\7-Zip\7z.exe" /b /low /wait "C:\Program Files (x86)\7-Zip\7z.exe" a -tzip "%%x.zip" "%%x\" 但我无法弄清楚如何删除原始文件夹并保留压缩文件。我尝试了许多不同的线路,但无法使其正常工作。

标签: batch-file compression backup scheduled-tasks 7zip


【解决方案1】:

假设您使用 7zip 作为命令行,您应该可以使用以下脚本:

@ECHO OFF
for /d %%a in (*) do (7za a -tzip %%~na.zip "%%a")
for /d %%a in (*) do (if exist "%%a\" del "%%a")
pause

要使用它,请在您提到的“logtype”文件夹中敲击批处理文件,然后运行它。

【讨论】:

  • 谢谢...我已经提交了最终解决方案,作为对我有用的答案。
【解决方案2】:

命令集是正确执行此类任务的正确方法。

command && command_OK || command_Fail

command_OK 将仅在command 成功完成时执行,command_Fail 将在出错时执行。这种模式的典型用法:

call %archiver% %file% && (del %file%) || (exit /b 1)

但在这种情况下,您不需要任何额外的命令。幸运的是,7zip 具有出色的 -sdel 选项,可以解决问题。

【讨论】:

    【解决方案3】:

    我最终选择了

    REM compress folders to zips
    for /d %%x in ("C:\Logs\*.*") do start "C:\Program Files (x86)\7-Zip\7z.exe" /b /low /wait "C:\Program Files (x86)\7-Zip\7z.exe" a -tzip "%%x.zip" "%%x\"
    
    REM delete the original folders used to create zips
    for /d %%F in ("C:\Logs\*") do rd /s /q "%%F"
    

    【讨论】:

    • 投反对票,因为这种解决方案不仅笨拙而且危险。您甚至都不检查文件夹是否压缩成功。
    【解决方案4】:

    这是我用于文件夹的内容。

    @echo off
    for /D %%d in (*) do (
    7z a t -mx9 -t7z -y "%%~nd.7z" "%%~fd" 
    if exist "%%~nd.7z" rmdir /s /q "%%~fd"
    else
    echo The file "%%~fd" DOES NOT exist
    pause
    )
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2012-02-23
      相关资源
      最近更新 更多