Pack contents of subfolders to a separate .zip file in Windows

I had a collection of e-books and video courses, each of them having _code_ folder containing sometimes even 30-40 subfolders and each of these subfolders containing sometimes even hundreds of thousands of files. I wanted to batch-pack contents of each folder into a separate .zip file.

The “contents” is a key here. I did not want to end up with a bunch of .zip files having one folder in its root.

That Artificial Guy has figured out a .bat file’s code for me:

@echo off
setlocal EnableDelayedExpansion

:: Change to the directory where the script is located
cd /d "%~dp0"

:: Iterate through each subfolder
for /d %%D in (*) do (
echo Processing folder: %%D
cd "%%D"
tar -a -c -f "..\%%D.zip" *.*
if !errorlevel! == 0 (
cd ..
echo Deleting folder: %%D
rmdir /s /q "%%D"
) else (
echo Failed to create zip for folder: %%D
cd ..
)
)

echo All done!

To run this script, you have to:

  1. Move it to a folder where you want to pack your subfolders
  2. Open Windows Terminal and cd-navigate to that folder
  3. Execute the script and watch its magic

Well… it was working like a charm, but I wanted more. I wanted to be able to run it in any folder and specify the folder it should operate in via first execution argument.

Artificial Guy has (as always) a solution even for that:

@echo off
setlocal EnableDelayedExpansion

:: Check if the directory path argument is provided
if "%~1"=="" (
echo No directory path provided.
echo Usage: %~nx0 [directory path]
exit /b 1
)

:: Change to the provided directory
cd /d "%~1" || (
echo Failed to change to directory: %~1
exit /b 1
)

:: Iterate through each subfolder
for /d %%D in (*) do (
echo Processing folder: %%D
cd "%%D"
tar -a -c -f "..\%%D.zip" *.*
if !errorlevel! == 0 (
cd ..
echo Deleting folder: %%D
rmdir /s /q "%%D"
) else (
echo Failed to create zip for folder: %%D
cd ..
)
)

echo All done!

And now… the best part.

You can achieve exactly the same effect in Total Commander. You just have to:

  1. Go to a destination folder (where you have all your subfolders)
  2. Mark all subfolders
  3. Press Alt+F5
  4. Check the following options:
    • Move to archive
    • Create separate archive, one per selected file/dir
    • Leave out base directory when packing folders
  5. Hit Enter or click OK

It is just… that I am too lazy… with all this clicking and clicking! :)

Leave a Reply