How can I create a batch job (.bat) that zip a folder?

53,789

Solution 1

Use the syntax

7z a -tzip archive.zip -r src\*.cpp src\*.h

so in your case, it'd be

7z a -t7z %filename% -r %pathtobackup%\*.doc

Source: http://sevenzip.sourceforge.jp/chm/cmdline/switches/recurse.htm

Solution 2

Install 7z and you can use this working example with delete script for files older than 7 days. What this script does, it zips the files from given 'input' folder to 'output' folder. In order to zip folders, you have to add /d or to zip all files within folder just modify the last "%%X".

REM This is a batch script to zip files in folder or add /d to zip folders.
REM This script is using 7z to zip files, installation is required - "[http://www.7-zip.org/a/7z938-x64.msi][1]"
REM Remember to point 'do' to 7z installed path 7z.exe

SET input1=D:\Backup\SampleFolder
SET input2=D:\Backup\SampleFolder2

SET output1=C:\ZipBackups\SampleFolder
SET output2=C:\ZipBackups\SampleFolder2

CD /d %input1%
for %%X in (*) do "C:\Program Files\7-Zip\7z.exe" a "%output1%\%%X.zip" "%%X"
FORFILES /P "%input1%" /M *.* /D -8 /C "cmd /c del @file"

CD /d %input2%
for %%X in (*) do "C:\Program Files\7-Zip\7z.exe" a "%output2%\%%X.zip" "%%X"
FORFILES /P "%input2%" /M *.* /D -8 /C "cmd /c del @file"

Solution 3

I have found a simple solution for this. Suppose you have multiple sub folders to be zipped in a folder. In that case, 1. Download and lnstall 7zip software. Then copy 7z.exe to the particular folder where you want to zip your subfolders.

in a notepad, copy and paste the following and save as .bat file. :

cd "your_Folder_path" for /d %%f in (*) do (7z a -t7z %%f.7z "your_Folder_path\%%f")

The double click to run the file.

In case you want to delete the original folders, add this before the closing brace :

rd /s /q "your_Folder_path\%%f"
Share:
53,789

Related videos on Youtube

Jason94
Author by

Jason94

Feed me technology!

Updated on September 18, 2022

Comments

  • Jason94
    Jason94 over 1 year

    From 7zip I've downloaded their command line tool 7za.exe, and I have to following script:

    echo off
    
    cls
    
    set zip ="C:\7za.exe"
    
    set filename="%date%.backup.zip"
    
    set pathtobackup="C:\MyDocs"
    
    %zip% -t7z %filename% %pathtobackup%\*.doc
    

    My intention is to backup all the doc files in MyDocs folder (including subfolders) and put them in a dated zip file. Afterwards I will move this file with robocopy to my server, but at the moment Im having some problems getting it to zip the files.

    Anyone have a clue? Anyway I can append a password for the file too?

    • and31415
      and31415 about 10 years
      You're "having some problems": care to elaborate? At a first glance, you're creating a .7z archive with a .zip extension. Also, you're relying on the %date% variable which may contain invalid, reserved characters.