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?

vcsjones
  • 722
  • 1
  • 8
  • 21
  • What's with the requirement to download 7zip from SF? Wy can't you install/copy from an internal source? – longneck Nov 08 '12 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 Nov 08 '12 at 21:54
  • If you are handing something out to customers why not build a self-extracting archive? – Zoredache Nov 09 '12 at 07: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 Nov 09 '12 at 14:04

1 Answers1

25

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
Peter Hahndorf
  • 14,058
  • 3
  • 41
  • 58