Batch file script to zip files

后端 未结 7 1453
夕颜
夕颜 2020-12-09 03:22

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 sin

7条回答
  •  鱼传尺愫
    2020-12-09 04:24

    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.

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

    @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.zip in 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.zip in the same folder containing all matching *.cmd files.


    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.

提交回复
热议问题