15

I need to unzip a file with powershell. The typical way I've seen everyone do this is by automating the shell with a script.

$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
$destinationFolder = $shellApplication.NameSpace($destination)
$destinationFolder.CopyHere($zipPackage.Items())

This isn't going to work for me, as Server Core doesn't have a shell, so there isn't one to automate. This gives an E_FAIL COM error.

Powershell doesn't seem to be able to do it on its own, and if I go 3rd party, I have to figure out a way to script getting the utility on to the server in the first place. 7-Zip was my go-to, but it doesn't seem like I can script the download and install of it. Sourceforge keeps spitting me back HTML files.

How can I completely script unzipping a zip file in Server 2012 Core?

4
  • What's with the requirement to download 7zip from SF? Wy can't you install/copy from an internal source?
    – longneck
    Commented Nov 8, 2012 at 21:33
  • @longneck The PS script I am producing is going to be handed out to customers; so the script has to be entirely self contained. I could host a zip utility ourselves, but that is another headache I don't want (legalese). I was just hoping there was a simple Cmdlet that could do this that got intro-ed in 2012.
    – vcsjones
    Commented Nov 8, 2012 at 21:54
  • If you are handing something out to customers why not build a self-extracting archive?
    – Zoredache
    Commented Nov 9, 2012 at 7:01
  • @Zoredache Well, that seemed like more work initially (our build system is already building ZIPs), I was hoping it would just be "real quick".
    – vcsjones
    Commented Nov 9, 2012 at 14:04

1 Answer 1

26

Server 2012 comes with Dot.NET 4.5 which has System.IO.Compression.ZipFile which has a ExtractToDirectory method. You should be able to use this from PowerShell.

Here is an example.

First you need to load the assembly ZipFile is in:

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null

Then extract the contents

[System.IO.Compression.ZipFile]::ExtractToDirectory($pathToZip, $targetDir)

Edit: If you have updated to PowerShell 5 (Windows Management Framework 5.0) you finally have native cmdlets:

Expand-Archive $pathToZip $targetDir
4
  • I just looked through System.IO.Compression and ZipFile isn't there. Is there an update to 4.5 that adds it?
    – Mike
    Commented Nov 9, 2012 at 13:46
  • It seems this was introduced in 4.5, but not present in 4.0. If you have 4.5 you should have it. Commented Nov 9, 2012 at 13:54
  • 6
    It's about damn time that there's a native solution for this.
    – MDMarra
    Commented Nov 9, 2012 at 15:49
  • Blog post derived from this answer Commented Aug 28, 2013 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .