PoshTip #1 – Unzip your archives

PoshTip #1 – Unzip Archive

Ok, I start a new serie of articles about PowerShell Tips.

You have the ability to unzip archives with PowerShell. You will ask me “But you can do it with 7zip!”
Yes, you are right. But as a sysadmin, you need to ensure that systems adhere to the security principle of least functionality. That is, essentially, you should not install useless additional software.

First method

As you can see, I create a function for flexibility:

Function Extract-ZIPFile($MyZipFile, $MyDestination)
{
    $ShellObj = new-object -com shell.application
    $MyZip = $ShellObj.NameSpace($MyZipfile)
    Foreach($Item in $MyZip.items()) {
        $ShellObj.Namespace($MyDestination).copyhere($Item)
    }
}

And then, you can simply use this function like that :

Extract-ZIPFile -MyZipFile C:\GET-CMD.zip -MyDestination C:\ExtractFolder\

Second method

To extract all files from a .zip archive file, you can also use the ExtractToDirectory static method. You need to add the System.IO.Compression.FileSystem assembly into your script :

Function Extract-ZIPFile($MyZipFile, $MyDestination) {

Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($MyZipFile, $MyDestination)

}

And then, you can use the function :

Extract-ZIPFile -MyZipFile C:\GET-CMD.zip -MyDestination C:\TMP
About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.