Skip to content

Unzip Multiple Archives (Optionally With Password Protection) Using PowerShell on Windows

Short version: You need 7-zip to go with it if you want to do the password protection bit

Most of the shell posts here are to do with Linux, and particularly bash, but today I’d like to share a useful Powershell nugget. By the way, to get a powershell, open up a command prompt (Win + R -> cmd [enter]) and type powershell. Just like that.

Now, I wanted to unzip a big folder of zip archives, protected with a simple password. Well, turns out that is relatively easy to do with PowerShell and 7-zip, both of which I had. BWAIN*dump got me started, and I changed it to work with password protection and added a couple refinements. The code:

$shell=new-object -com shell.application

$CurrentLocation=get-location

$CurrentPath=$CurrentLocation.path

$Location=$shell.namespace($CurrentPath)

$ZipFiles = get-childitem *2010*.zip | where {$_.length -gt 22} | sort-object -property LastWriteTime -descending

$ZipFiles.count | out-default

foreach ($ZipFile in $ZipFiles)

{
C:\7z.exe e -y -oC:\directory -psomepass $ZipFile.Name
}

Explanations:

  • The first four lines are basic setup, saying “we’re going to work in the current directory”
  • $ZipFiles = get-childitem *2010*.zip – get all zip files that have “2010” in the name. This was for my own purposes, you could instead use *.zip for all zip files.
  • | where {$_.length -gt 22} – a pipe to select all files with a size of 22 bytes or more, as I didn’t want any empty files to be included
  • | sort-object -property LastWriteTime -descending – a pipe to sort by date modified, descending. Handy if you are only doing a subset of files, eg to test.
  • foreach ($ZipFile in $ZipFiles) – loop through the files
  • C:\7z.exe e -y -oC:\directory -psomepass $ZipFile.Name – the important bit, using 7-zip to extract the password-ed files. THis does assume they have all the same password, incidentally. If you have 7-zip in the same directory as the files (as I did), you can write:
    \7z e -y -oC:\directory -psomepass $ZipFile.Name, but you need to escape the 7 of “7z” for some reason. Note there are no spaces between -o and the output directory, nor -p and the password. -y just means answer “yes” to all questions, making it non-interactive. This will overwrite stuff that has the same name, I’m happy with that but you might not be.

Anyway, that code should extract files from zip archives with a password to a specified directory. Modify it to your purposes as I did!

3 thoughts on “Unzip Multiple Archives (Optionally With Password Protection) Using PowerShell on Windows”

Tell us what's on your mind

Discover more from Rob's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading