Windows batch script to unzip files in a directory
Asked Answered
S

5

11

I want to unzip all files in a certain directory and preserve the folder names when unzipped.

The following batch script doesn't quite do the trick. It just throws a bunch of the files without putting them into a folder and doesn't even finish.

What's wrong here?

for /F %%I IN ('dir /b /s *.zip') DO (

    "C:\Program Files (x86)\7-Zip\7z.exe" x -y -o"%%~dpI" "%%I" 
)
Softener answered 13/6, 2013 at 1:38 Comment(2)
Is it possible that some of your zip files have a space in the name? If so your 1st line should be: for /F "usebackq" %%I IN (dir /b /s "*.zip") DO (Scream
Try this: for /F "delims=" %%I IN ('dir /b /s/a-d *.zip') DO ( .Haemolysin
H
36

Try this:

for /R "C:\root\folder" %%I in ("*.zip") do (
  "%ProgramFiles(x86)%\7-Zip\7z.exe" x -y -o"%%~dpI" "%%~fI" 
)

or (if you want to extract the files into a folder named after the Zip-file):

for /R "C:\root\folder" %%I in ("*.zip") do (
  "%ProgramFiles(x86)%\7-Zip\7z.exe" x -y -o"%%~dpnI" "%%~fI" 
)
Heida answered 13/6, 2013 at 8:30 Comment(1)
what should i do if i need to extract the file to a different destination??Overstudy
B
7

Ansgar's response above was pretty much perfect for me but I also wanted to delete archives afterwards if extraction was successful. I found this and incorporated it into the above to give:

for /R "Destination_Folder" %%I in ("*.zip") do (
  "%ProgramFiles%\7-Zip\7z.exe" x -y -aos -o"%%~dpI" "%%~fI"
  "if errorlevel 1 goto :error"
    del "%%~fI"
  ":error"
)
Bramblett answered 2/9, 2015 at 10:36 Comment(1)
Is it possible to extract to a different directory?Overstudy
P
1

Try this.

@echo off
for /F "delims=" %%I IN (' dir /b /s /a-d *.zip ') DO (
    "C:\Program Files (x86)\7-Zip\7z.exe" x -y -o"%%~dpI\%%~nI" "%%I" 
)
pause
Polaroid answered 13/6, 2013 at 7:37 Comment(2)
@moinkhan I'd be happy to. Which part is confusing to you?Polaroid
@foxidirve pls explain the perimeters in the loop & the whole idea,how its worksAphasic
S
0

Is it possible that some of your zip files have a space in the name? If so your 1st line should be:

for /F "usebackq" %%I IN (`dir /b /s "*.zip"`) DO (

Note the use of ` instead of ' See FOR /?

Scream answered 13/6, 2013 at 2:1 Comment(1)
And using "delims=" is necessary to handle long names.Polaroid
B
0

As PowerShell script (and without a 3rd party tool) you can run:

#get the list of zip files from the current directory
$dir = dir *.zip
#go through each zip file in the directory variable
foreach($item in $dir)
  {
    Expand-Archive -Path $item -DestinationPath ($item -replace '.zip','') -Force
  }

Taken from Microsoft forum posted by user 'pestell159'.

Balata answered 15/11, 2023 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.