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