Compress Each Subfolder Separately with 7-Zip
Compressing multiple folders individually can be tedious when done
manually through a graphical interface. This guide demonstrates how to
automate 7-Zip using the command line across Windows Command Prompt,
PowerShell, and Linux Bash. By running a simple loop script, you can
automatically scan a directory, iterate through each individual
subdirectory, and compress each one into its own standalone
.7z or .zip archive.
Prerequisites
Ensure 7-Zip is installed on your system. On Windows, the default
installation path is typically
C:\Program Files\7-Zip\7z.exe. You can either call the
executable using its full path or add the 7-Zip installation directory
to your system's PATH environment variable.
Method 1: Windows Command Prompt (CMD)
Command Prompt One-Liner
Open Command Prompt, navigate to the parent folder containing your
subdirectories using the cd command, and run the following
command:
for /d %X in (*) do "C:\Program Files\7-Zip\7z.exe" a "%X.7z" "%X"In a Batch Script (.bat)
If you are saving the command inside a .bat file, double
the percent signs (%%X):
@echo off
for /d %%X in (*) do (
"C:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X"
)
pause/d: Limits the loop to directories only.%X: Represents the current folder name in the loop.a: Tells 7-Zip to add files to an archive."%X.7z": Sets the output archive name to match the folder name. Change.7zto.zipif you prefer standard ZIP archives.
Method 2: Windows PowerShell
PowerShell offers a modern and flexible approach using the
Get-ChildItem cmdlet. Open PowerShell, navigate to your
target directory, and execute:
Get-ChildItem -Directory | ForEach-Object {
& "C:\Program Files\7-Zip\7z.exe" a "$($_.Name).7z" "$($_.FullName)"
}-Directory: Ensures only folders are retrieved, ignoring loose files in the root folder.ForEach-Object: Iterates through each folder returned.&: The call operator used to execute the 7-Zip binary.$($_.Name).7z: Uses the folder's name for the archive.$($_.FullName): Supplies the full path of the source directory.
Method 3: Linux / macOS (Bash)
If you are using Linux or macOS with p7zip installed,
use a Bash for loop:
for d in */; do
7z a "${d%/}.7z" "$d"
done*/: Matches all subdirectories in the current path.${d%/}: Strips the trailing slash from the directory name so the resulting archive is namedfoldername.7zinstead offoldername/.7z.