Friday, May 13, 2011

DOS Batch script to unzip a ZIP file and then delete the ZIP

I'm not sure about you, but 95% of the time when I have a ZIP file, all I want to do is unzip. I don't want to browse it in Windows Explorer and I sure don't want to open it in WinZip. When StuffIt Expander was easy to install and use, this tool had an option to do exactly this. Double-click the ZIP, StuffIt would unzip with a minimal UI (if any), delete the ZIP, and then quit. This is no longer an (obvious) option, so I thought, why not write my own script for this?

You'll need to install 7-Zip and include the executable somewhere in your PATH, or update this script to explicitly point to your 7-Zip executable.

@echo off

REM Get the base filename (without extension) and the extension (with the period).
for /f "tokens=* delims= " %%F in ('echo %1') do (
set base=%%~nF
set ext=%%~xF

REM Create a new dir to hold the ZIP file and the ZIP contents
mkdir "%base% folder"
move %1 "%base% folder"
cd "%base% folder"

REM Unzip the file and then delete the ZIP file.
7za x "%base%%ext%" && del "%base%%ext%"

REM Something went wrong with the unzip.
REM Move the ZIP file up a level, remove any other files in this dir,
REM then remove this dir.
move "%base%%ext%" ..
del/q *
cd ..
rmdir "%base% folder"
goto END

REM Check if there is exactly one file in this dir.
ls -1 | wc -l | findstr "\<1$" > nul

REM Move the file up a level and then remove this dir.
move * ..
cd ..
rmdir "%base% folder"