I have a .zip
file and need to unpack its entire content using Powershell. I'm doing this but it doesn't seem to work:
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("C:\a.zip")
MkDir("C:\a")
foreach ($item in $zip.items()) {
$shell.Namespace("C:\a").CopyHere($item)
}
What's wrong? The directory C:\a
is still empty.
Here is a simple way using ExtractToDirectory from System.IO.Compression.ZipFile:
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
param([string]$zipfile, [string]$outpath)
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
Unzip "C:\a.zip" "C:\a"
Note that if the target folder doesn't exist, ExtractToDirectory will create it.
How to Compress and Extract files
In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:
Expand-Archive c:\a.zip -DestinationPath c:\a
PowerShell v5.1 it seems this is slightly different from v5. As per the MS document it has to have a -Path parameter to specify the archive file path.
Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference
Or else this can be actual path as below,
Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference
Expand-Archive Doc
Hey Its working for me..
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
$shell.Namespace("destination where files need to unzip").CopyHere($item)
}
Using expand-archive
but auto-creating directories named after the archive:
function unzip ($file) {
$dirname = (Get-Item $file).Basename
New-Item -Force -ItemType directory -Path $dirname
expand-archive $file -OutputPath $dirname -ShowProgress
}
function unzip {
param (
[string]$archiveFilePath,
[string]$destinationPath
)
if ($archiveFilePath -notlike '?:\*') {
$archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
}
if ($destinationPath -notlike '?:\*') {
$destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
}
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
$archive = [System.IO.Compression.ZipArchive]::new($archiveFile)
if (Test-Path $destinationPath) {
foreach ($item in $archive.Entries) {
$destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)
if ($destinationItemPath -like '*/') {
New-Item $destinationItemPath -Force -ItemType Directory > $null
} else {
New-Item $destinationItemPath -Force -ItemType File > $null
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
}
}
} else {
[System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
}
}
Using:
unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'