Read content of compressed file (.zip file) using PowerShell
Quote from HeelpBook on March 23, 2021, 12:27 amAs the subject of the topic, how to list/read the content of a .zip archive using Powershell?
As the subject of the topic, how to list/read the content of a .zip archive using Powershell?
Quote from HeelpBook on March 23, 2021, 12:29 amTo read the content of the compressed file we will use the ZipArchive class and Stream class (using Microsoft .NET). Here is an example:
Add-Type -AssemblyName System.IO.Compression
$ZipFile = 'C:\Temp\Zip\SubFoldersAndFilesZipped.zip'
$Stream = New-Object IO.FileStream($ZipFile, [IO.FileMode]::Open)
$ZipArchive = New-Object IO.Compression.ZipArchive($Stream)$ZipArchive.Entries |
Select-Object Name,
@{Name="File Path";Expression={$_.FullName}},
@{Name="Compressed Size (KB)";Expression={"{0:N2}" -f($_.CompressedLength/1kb)}},
@{Name="UnCompressed Size (KB)";Expression={"{0:N2}" -f($_.Length/1kb)}},
@{Name="File Date";Expression={$_.LastWriteTime}} | Out-GridView$ZipArchive.Dispose()
$Stream.Close()
$Stream.Dispose()Take note that if you do not want to list the content in a grid view it is sufficient to remove the | Out-GridView from the above code to list the result directly in Powershell console.
IMPORTANT: We have used ZipArchive and Stream classes since both have the Dispose method and we avoid locking the compressed file (zip) while running the script in the client application (PowerShell ISE, for example).
To read the content of the compressed file we will use the ZipArchive class and Stream class (using Microsoft .NET). Here is an example:
Add-Type -AssemblyName System.IO.Compression
$ZipFile = 'C:\Temp\Zip\SubFoldersAndFilesZipped.zip'
$Stream = New-Object IO.FileStream($ZipFile, [IO.FileMode]::Open)
$ZipArchive = New-Object IO.Compression.ZipArchive($Stream)
$ZipArchive.Entries |
Select-Object Name,
@{Name="File Path";Expression={$_.FullName}},
@{Name="Compressed Size (KB)";Expression={"{0:N2}" -f($_.CompressedLength/1kb)}},
@{Name="UnCompressed Size (KB)";Expression={"{0:N2}" -f($_.Length/1kb)}},
@{Name="File Date";Expression={$_.LastWriteTime}} | Out-GridView
$ZipArchive.Dispose()
$Stream.Close()
$Stream.Dispose()
Take note that if you do not want to list the content in a grid view it is sufficient to remove the | Out-GridView from the above code to list the result directly in Powershell console.
IMPORTANT: We have used ZipArchive and Stream classes since both have the Dispose method and we avoid locking the compressed file (zip) while running the script in the client application (PowerShell ISE, for example).