#PSTip Determine compression ratio of compressed files

In the previous #PSTip Compress files and folders with System.IO.Compression.FileSystem class, a .zip file was created and extracted. Now it might be good to know the compression ratio to see how much storage space has been saved by compressing the files. Using a ForEach-Object loop in combination with the Open method of this class we can determine the total size, compressed size, and the ratio of compression of a .zip file.

[System.IO.Compression.ZipFile]::Open("c:\testing\colorcopy\yourfile.zip",'Read') | ForEach-Object {

     $_.Entries | ForEach-Object -Begin {
        [long]$TotalCompressed = $null
        [long]$TotalSize = $null
    } -Process {
        $TotalCompressed += $_.CompressedLength
        $TotalSize += $_.Length
    } -End {
            FileSize = $TotalSize
            CompressedSize = $TotalCompressed
            Ratio = "{0:P2}" -f ($TotalCompressed / $TotalSize)

About the author: Jaap Brasser

Jaap is a Senior System Engineer in the Financial Services industry. He focuses on Microsoft and related technologies and has a passion for PowerShell. In his spare time he maintains his Blog, Twitter feed, @Jaap_Brasser, and contributes on the Official Scripting Guys Forum and Windows PowerShell TechNet forums

Related Posts

%d bloggers like this: