Batch file script to folder in zip files

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 or folders)under them.

Directory master
folder 1:
  file1
  file2
folder 2:
  file 3
  file 4
  folder x

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.

1.zip (only contains file1 and file2 -without folder 1 )
2.zip (only contains file3 and file4 and folder x -without folder 2- )

the zip file dont be contain the folder 1 or folder 2

this code do it, but compress to ther subfolder as 1.zip ( folder 1 file1 file2 ) 2.zip ( folder 2( file3 file4 folder x ) )

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

Upvotes: 2

Views: 1857

Answers (1)

SomeDude
SomeDude

Reputation: 14238

I believe you can achieve what you want with the below code which uses 7-zip to zip files:

@echo off
setlocal enabledelayedexpansion
set YOUR_DIR=%1
set OWNING_DIR=%~dp0
set zipext=.zip

for /f "tokens=*" %%L in ('dir /b "%YOUR_DIR%"' ) do (
   set FOLDER_NAME=%%L
     set zipname=%OWNING_DIR%\!FOLDER_NAME!%zipext%
     set ERRORLEVEL=0
     type NUL
     set DIR_TO_CHECK=%YOUR_DIR%\!FOLDER_NAME!
     IF EXIST "!DIR_TO_CHECK!"\* (
       pushd %YOUR_DIR%\!FOLDER_NAME! >NUL 2>&1
       if %ERRORLEVEL% equ 0 (
         for /f "tokens=*" %%a in ( 'dir /b') do (
            "C:\Program Files\7-Zip\7z.exe" a  "!zipname!" "%%a"             
          )
       )
       popd
      ) 
   )

Copy this to a batch file called zip_files.bat and call it using

zip_files "Directory_master"

Upvotes: -1

Related Questions