Script 7-Zip to Extract to Archive-Named Folders
Automating 7-Zip to unpack compressed files into dedicated folders matching their original filenames saves time and prevents file clutter when handling bulk downloads. This guide demonstrates how to script 7-Zip via the Windows Command Prompt (Batch) and PowerShell using standard 7-Zip command-line switches and path variables.
Understanding the 7-Zip Command Syntax
The core command to extract files with full paths preserved is
x. To specify the destination directory, 7-Zip uses the
-o switch.
A critical syntax rule for 7-Zip is that there must be no
space between -o and the directory path:
"C:\Program Files\7-Zip\7z.exe" x "archive.zip" -o"archive" -yx: Extracts files with full paths.-o"archive": Specifies the output directory named "archive".-y: Automatically confirms all prompts (assumes "Yes" on overwrite).
Method 1: Windows Batch Script
A Windows Batch file (.bat) uses a FOR loop
combined with the %~nI parameter, which resolves to the
file name without its extension.
Batch Script (.bat file)
Create a text file, name it extract_all.bat, and place
it in the folder containing your archives:
@echo off
set "SEVENZIP=C:\Program Files\7-Zip\7z.exe"
for %%I in (*.zip *.7z *.rar) do (
"%SEVENZIP%" x "%%I" -o"%%~dpnI" -y
)
pauseParameter Breakdown:
*.zip *.7z *.rar: Iterates through all specified archive formats in the directory.%%~dpnI:d= Drive letterp= Folder pathn= File name without extension
This creates an output directory with the same name and in the same location as the archive.
Method 2: PowerShell Script
PowerShell provides better error handling and allows you to process
files recursively through subdirectories using the BaseName
property.
One-Liner (Current Directory)
Run this directly inside a PowerShell terminal in your target folder:
Get-ChildItem -File -Include *.zip, *.7z, *.rar | ForEach-Object {
& "C:\Program Files\7-Zip\7z.exe" x $_.FullName -o"$($_.DirectoryName)\$($_.BaseName)" -y
}Recursive Script (.ps1 file)
To scan subdirectories recursively and extract each archive into a folder matching its name at its current location:
$7zPath = "C:\Program Files\7-Zip\7z.exe"
$targetDir = "C:\Path\To\Archives"
Get-ChildItem -Path $targetDir -Recurse -File | Where-Object { $_.Extension -match '\.(zip|7z|rar|tar|gz)$' } | ForEach-Object {
$outputFolder = Join-Path -Path $_.DirectoryName -ChildPath $_.BaseName
& $7zPath x $_.FullName -o"$outputFolder" -y
}Parameter Breakdown:
$_.FullName: The full path to the archive file.$_.DirectoryName: The folder containing the archive.$_.BaseName: The filename without the file extension.Join-Path: Safely constructs the destination path using the directory and the archive's base name.