批处理脚本 - 使用 7-zip 进行压缩

问题描述 投票:0回答:1

我正在尝试在 Batch 中制作一个脚本,以便在每个包含具有某种扩展名的文件的文件夹中制作一个 zip,但问题是 7-zip 无论如何都会压缩。即使他没有找到具有良好扩展名的文件,他也会创建一个空的 zip。 下面是我已经做过的事情。

setlocal enableDelayedExpansion
set /p ext="Write with the . which extension you want to zip. : "
set "currentdir="

for /f "delims=" %%b in ('dir /b /s /a-d "C:\Users\546802\Desktop\Test"') do (
 if "!currentdir!" neq "%%~dpb" ( 
  set "currentdir=%%~dpb"
  for /d %%c IN ("%%~dpb.") do "c:\Program Files\7-Zip\7z.exe" a -mx "%%~dpb%%~nxc.zip" %%c\*%ext% )
)

我该如何解决这个问题? 7-zip 有命令可以避免这种情况吗? 我阅读了多个有关 7-zip 命令的主题,但没有找到满足我需要的命令。

batch-file 7zip
1个回答
1
投票

此 ZIP 存档文件创建任务的批处理文件是:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileExtension="

rem Prompt the user in a loop until entering really a file extension.
rem Pressing just RETURN or ENTER results in prompting the user again.
rem Double quotes are always removed from input string and there must
rem be entered something else than just straight double quotes one or
rem more times. A dot at beginning of the file extension is always
rem removed and there must be entered more than just one dot. The file
rem extension entered by the user cannot contain / or \ or . or any
rem other character not allowed in a file extension according to the
rem definition by Microsoft.

:PromptUser
set /P "FileExtension=Enter the file extension to zip: " || goto PromptUser
set "FileExtension=%FileExtension:"=%"
if not defined FileExtension goto PromptUser
if "%FileExtension:~0,1%" == "." set "FileExtension=%FileExtension:~1%"
if not defined FileExtension goto PromptUser
set "FailedSyntaxCheck=1"
for /F "delims=*./:<>?\|" %%I in ("%FileExtension%") do if not "%%I" == "%FileExtension%" (goto PromptUser) else set "FailedSyntaxCheck="
if defined FailedSyntaxCheck goto PromptUser

for /F "delims=" %%I in ('dir "%USERPROFILE%\Desktop\Test" /AD-L /B /S 2^>nul') do if exist "%%I\*.%FileExtension%" "%ProgramFiles%\7-Zip\7z.exe" a -bso0 -bsp0 -mx=9 -r- -tzip -y -- "%%I\%%~nxI.zip" "%%I\*.%FileExtension%"
endlocal

批处理文件不是 100% 故障安全。文件扩展名语法验证不是 100%。因此,用户仍然可以输入对文件扩展名无效的字符串,如 Microsoft 在有关命名文件、路径和命名空间的文档页面上所述。

如果存在名称为 Test.txt

directory
并且用户输入
.txt
或仅输入
txt
作为文件扩展名,则此代码中使用的简单 IF 条件为 true,尽管
Test.txt
是一个文件夹而不是一个文件,因此 7-Zip 仍然被执行。如果也应该处理此类用例,则可以改进代码以使条件更加准确。

使用的 7-Zip 开关在 7-Zip 的帮助中进行了描述。双击

7-Zip
程序文件文件夹中的文件 7-zip.chm 打开帮助,单击列表项命令行版本上的第一个选项卡内容,然后阅读有关 的所有引用帮助页面命令行语法命令开关

在包含具有指定文件扩展名的文件的文件夹内创建 ZIP 文件。将

"%%I\%%~nxI.zip"
替换为
"%%I.zip"
后,可以在包含具有指定文件扩展名的文件的目录的父目录中创建 ZIP 文件。该问题不包含包含用户输入
txt
.cmd
执行批处理文件之前和之后包含文件的目录树的明确信息,无法真正了解此 ZIP 存档文件创建任务的所有要求。

要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。

  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • rem /?
  • set /?
  • setlocal /?
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.