Thursday 15 January 2009

PowerShell script to unzip many files

Yeah, I know, I keep saying I’ll post more and all I do is post less.  Well the back half of 2008 kind of got derailed by unavoidable ‘life’ stuff and to be quite honest I haven’t yet decided if blogging will be one of my priorities in 2009.  Rest assured that if it is, I’ll be doing it properly and a redesign will be part of that commitment.  For now though, I’m back to using this as a holding space.  If I don’t want to lose something, and it might come in handy for someone else, it’ll end up in the blog.  Otherwise... well, we’ll see.

So here it is.  Say you have a folder full of zip files at j:\stuff.  Running this script (with j:\stuff as the current location) will unzip the contents of those zip files to j:\stuff.

$shell=new-object -com shell.application

$CurrentLocation=get-location

$CurrentPath=$CurrentLocation.path

$Location=$shell.namespace($CurrentPath)

$ZipFiles = get-childitem *.zip

$ZipFiles.count | out-default

foreach ($ZipFile in $ZipFiles)

{

$ZipFile.fullname | out-default

$ZipFolder = $shell.namespace($ZipFile.fullname)

$Location.Copyhere($ZipFolder.items())

}

If you also want to delete the source zip files, you can add remove-item $ZipFile after the line beginning $Location.Copyhere.  The reason I didn’t include that in the sample above is I strongly advise you (see my usual disclaimer) to run the script and make sure you’re satisfied the zip files unzipped properly before you go letting it delete anything!

Enjoy.

3 comments:

  1. what if file is password protected, how can i supply password in script..

    ReplyDelete
  2. I wish I could help, but that's beyond my meagre scripting skills. You could check this out... http://code.msdn.microsoft.com/DotNetZip.

    ReplyDelete
  3. Thanks for the help TechieBird! PowerShell can be kinda handy - it's nice to have a decent shell on Windows :)

    I know this is a bit late for saurav probably, but for anyone else looking: You can use 7-zip in the loop in the above script to extract password-protected files, thus:

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

    I've written about it here. Incidentally, it helped me uncover a misconfiguration which was preventing any of my posts being displayed to anyone else, so double thanks :D

    ReplyDelete

Creative Commons License This work by TechieBird is licensed under a Creative Commons Attribution-No Derivative Works 2.0 UK: England & Wales License.