windows 批处理文件脚本以压缩文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20485419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:09:54  来源:igfitidea点击:

Batch file script to zip files

windowsbatch-file

提问by user3085265

i have a folder structure in this pattern. I've just shown two sub directories and 2 files in each but generally I have n number of subdirectories at a single level and single level of files (but can be n number of files)under them.

我有这种模式的文件夹结构。我刚刚显示了两个子目录和每个文件中的 2 个文件,但通常我在单个级别和单个级别的文件(但可以是 n 个文件)下有 n 个子目录。

Directory master
subDirectory x:
  file1
  file2
Directory y:
  file 3
  file 4

I need to create a windows script, a batch file to run from the master directory and give me two zip files x.zip and y.zip containing their respective files.

我需要创建一个 Windows 脚本,一个从主目录运行的批处理文件,并给我两个包含各自文件的 zip 文件 x.zip 和 y.zip。

I know my script has to use for and zip commands but I am going bonkers trying to get it to work as I can't understand from the syntax of these commands and googling doesnt seem to help.

我知道我的脚本必须使用 for 和 zip 命令,但我正在疯狂地尝试让它工作,因为我无法从这些命令的语法中理解并且谷歌搜索似乎没有帮助。

I found a command like this for %f in ("*.*") do zip "%~nf.zip" "%f"but it seems to be working only if the files are directly there without subfolders.

我找到了一个这样的命令, for %f in ("*.*") do zip "%~nf.zip" "%f"但它似乎只有当文件直接存在而没有子文件夹时才有效。

回答by Magoo

for /d %%a in (*) do (ECHO zip -r -p "%%~na.zip" ".\%%a\*")

should work from within a batch.

应该在一个批次内工作。

Note that I've included an ECHOto simply SHOW the command that is proposed. You'd need to remove the ECHOkeywor to EXECUTE the commands.

请注意,我已经包含了一个ECHO来简单地显示建议的命令。您需要删除ECHO关键字才能执行命令。

回答by Arun Nallamayan

I know its too late but if you still wanna try

我知道为时已晚 但如果你还想试试

for /d %%X in (*) do (for /d %%a in (%%X) do ( "C:\Program Files-Zipz.exe" a -tzip "%%X.zip" ".\%%a\" ))

here * is the current folder. for more options try this link

这里 * 是当前文件夹。有关更多选择,请尝试此链接

回答by PodTech.io

No external dependency on 7zip or ZIP - create a vbs script and execute:

没有对 7zip 或 ZIP 的外部依赖 - 创建一个 vbs 脚本并执行:

    @ECHO Zipping
    mkdir %TEMPDIR%
    xcopy /y /s %FILETOZIP% %TEMPDIR%
    echo Set objArgs = WScript.Arguments > _zipIt.vbs
    echo InputFolder = objArgs(0) >> _zipIt.vbs
    echo ZipFile = objArgs(1) >> _zipIt.vbs
    echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
    echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
    echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
    echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
    @ECHO *******************************************
    @ECHO Zipping, please wait..
    echo wScript.Sleep 12000 >> _zipIt.vbs
    CScript  _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
    del _zipIt.vbs
    rmdir /s /q  %TEMPDIR%

    @ECHO *******************************************
    @ECHO      ZIP Completed

回答by m3nda

You're near :)

你就在附近:)

First, the batch (%%variable) and Windows CMD (%variable) uses different variable naming. Second, i dont figure out how do you use zip from CMD. This is from Linux users i think. Use built-in zip manipulation is not like easy on Win, and even harder with batch scripting.

首先,批处理(%%variable)和Windows CMD(%variable)使用不同的变量命名。其次,我不知道您如何使用 CMD 中的 zip。我认为这是来自 Linux 用户。在 Win 上使用内置的 zip 操作并不容易,在批处理脚本中更难。

But you're lucky anyway. I got (extracted to target folder) zip.exe and cygwin1.dll from the cygwin package (3mb filesize both together) and start play with it right now.

但无论如何你是幸运的。我从 cygwin 包中得到(提取到目标文件夹)zip.exe 和 cygwin1.dll(三个文件大小一起),现在就开始使用它。

Of course, i use CMD for better/faster testing instead batch. Only remember modify the %varname to %%varname before blame me :P

当然,我使用 CMD 进行更好/更快的测试而不是批处理。只记得在责备我之前将 %varname 修改为 %%varname :P

for /d %d in (*) do zip -r %d %d

for /d %d in (*) do zip -r %d %d

Explanation: for /d ...that matches any folder inside. Only folder ignoring files. (use for /f to filesmatch) for /d %d in ...the %d tells cmd wich name do you wanna assign to your variable. I put d to match widh d (directory meaning). for /d %d in (*) ...Very important. That suposses that I CDto desired folder, or run from. (*)this will mean all on THIS dir, because we use /dthe files are not processed so no need to set a pattern, even if you can get only some folders if you need. You can use absolute paths. Not sure about issues with relatives from batch. for /d %d in (*) do zip -r ...Do ZIP is obvious. (exec zip itself and see the help display to use your custom rules). r- is for recursive, so anyting will be added. for /d %d in (*) do zip -r %d %dThe first %d is the zip name. You can try with myzip.zip, but if will fail because if you have 2 or more folders the second cannot gave the name of the first and will not try to overwrite without more params. So, we pass %d to both, wich is the current for iteration folder name zipped into a file with the folder name. Is not neccesary to append ".zip" to name.

说明: for /d ...匹配里面的任何文件夹。仅文件夹忽略文件。(用于 /f 到文件匹配) for /d %d in ...%d 告诉 cmd 你想分配给你的变量的名字。我把 d 与 widh d 匹配(目录含义)。 for /d %d in (*) ...很重要。这假设我CD到所需的文件夹,或从中运行。(*)这将意味着所有在这个目录上,因为我们使用/d的文件没有被处理,所以不需要设置模式,即使你只能在需要时获得一些文件夹。您可以使用绝对路径。不确定批次亲戚的问题。 for /d %d in (*) do zip -r ...做ZIP是显而易见的。(执行 zip 本身并查看帮助显示以使用您的自定义规则)。r- 用于递归,因此将添加任何内容。 for /d %d in (*) do zip -r %d %d第一个 %d 是 zip 名称. 您可以尝试使用 myzip.zip,但是如果会失败,因为如果您有 2 个或更多文件夹,则第二个文件夹无法提供第一个文件夹的名称,并且不会尝试在没有更多参数的情况下覆盖。因此,我们将 %d 传递给两者,这是当前迭代文件夹名称压缩到具有文件夹名称的文件中。不需要将“.zip”附加到名称。

Is pretty short than i expected when start to play with.

开始玩时比我预期的要短。

回答by Patrick Burwell

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

这是归档个人的正确语法;批处理文件夹作为单独的压缩文件...

for /d %%X in (*) do "c:\Program Files-Zipz.exe" a -mx "%%X.zip" "%%X\*"

回答by Matt

I like PodTech.io's answer to achieve this without additional tools. For me, it did not run out of the box, so I had to slightly change it. I am not sure if the command wScript.Sleep 12000(12 sec delay) in the original script is required or not, so I kept it.

我喜欢PodTech.io的答案,无需额外工具即可实现这一目标。对我来说,它没有开箱即用,所以我不得不稍微改变它。我不确定是否wScript.Sleep 12000需要原始脚本中的命令(12 秒延迟),所以我保留了它。

Here's the modified script Zip.cmdbased on his answer, which works fine on my end:

这是Zip.cmd根据他的回答修改后的脚本,对我来说效果很好:

@echo off   
if "%1"=="" goto end

setlocal
set TEMPDIR=%TEMP%\ZIP
set FILETOZIP=%1
set OUTPUTZIP=%2.zip
if "%2"=="" set OUTPUTZIP=%1.zip

:: preparing VBS script
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo Set fso = WScript.CreateObject("Scripting.FileSystemObject") >> _zipIt.vbs
echo Set objZipFile = fso.CreateTextFile(ZipFile, True) >> _zipIt.vbs
echo objZipFile.Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo objZipFile.Close >> _zipIt.vbs
echo Set objShell = WScript.CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo Set objZip = objShell.NameSpace(fso.GetAbsolutePathName(ZipFile)) >> _zipIt.vbs
echo if not (objZip is nothing) then  >> _zipIt.vbs
echo    objZip.CopyHere(source) >> _zipIt.vbs
echo    wScript.Sleep 12000 >> _zipIt.vbs
echo end if >> _zipIt.vbs

@ECHO Zipping, please wait...
mkdir %TEMPDIR%
xcopy /y /s %FILETOZIP% %TEMPDIR%
WScript _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
del _zipIt.vbs
rmdir /s /q  %TEMPDIR%

@ECHO ZIP Completed.
:end

Usage:

用法:

  • One parameter (no wildcards allowed here):

    Zip FileToZip.txt

    will create FileToZip.txt.zipin the same folder containing the zipped file FileToZip.txt.

  • Two parameters (optionally with wildcards for the first parameter), e.g.

    Zip *.cmd Scripts

    creates Scripts.zipin the same folder containing all matching *.cmdfiles.

  • 一个参数(此处不允许使用通配符):

    Zip FileToZip.txt

    FileToZip.txt.zip在包含压缩文件的同一文件夹中创建FileToZip.txt

  • 两个参数(可选用通配符作为第一个参数),例如

    压缩 *.cmd 脚本

    Scripts.zip在包含所有匹配*.cmd文件的同一文件夹中创建。



Note:If you want to debug the VBS script, check out this hint, it describes how to activate the debugger to go through it step by step.

注意:如果您想调试 VBS 脚本, 请查看此提示,它描述了如何激活调试器以逐步完成它。

回答by Abhijeet

This is linkby Tomashas a well written script to zip contents of a folder.

这是由Tomas提供的链接,它有一个编写良好的脚本来压缩文件夹的内容。

To make it work just copy the script into a batch file and execute it by specifying the folder to be zipped(source).

要使其工作,只需将脚本复制到批处理文件中,然后通过指定要压缩的文件夹(源)来执行它。

No need to mention destination directory as it is defaulted in the script to Desktop ("%USERPROFILE%\Desktop")

无需提及目标目录,因为它在脚本中默认为桌面(“%USERPROFILE%\Desktop”)

Copying the script here, just incase the web-link is down:

在此处复制脚本,以防万一网络链接已关闭:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET sourceDirPath=%1
IF [%2] EQU [] (
  SET destinationDirPath="%USERPROFILE%\Desktop"
) ELSE (
  SET destinationDirPath="%2"
)
IF [%3] EQU [] (
  SET destinationFileName="%~n1%.zip"
) ELSE (
  SET destinationFileName="%3"
)
SET tempFilePath=%TEMP%\FilesToZip.txt
TYPE NUL > %tempFilePath%

FOR /F "DELIMS=*" %%i IN ('DIR /B /S /A-D "%sourceDirPath%"') DO (
  SET filePath=%%i
  SET dirPath=%%~dpi
  SET dirPath=!dirPath:~0,-1!
  SET dirPath=!dirPath:%sourceDirPath%=!
  SET dirPath=!dirPath:%sourceDirPath%=!
  ECHO .SET DestinationDir=!dirPath! >> %tempFilePath%
  ECHO "!filePath!" >> %tempFilePath%
)

MAKECAB /D MaxDiskSize=0 /D CompressionType=MSZIP /D Cabinet=ON /D Compress=ON /D UniqueFiles=OFF /D DiskDirectoryTemplate=%destinationDirPath% /D CabinetNameTemplate=%destinationFileName%  /F %tempFilePath% > NUL 2>&1

DEL setup.inf > NUL 2>&1
DEL setup.rpt > NUL 2>&1
DEL %tempFilePath% > NUL 2>&1