#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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
[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 {
        [pscustomobject]@{
            FileSize = $TotalSize
            CompressedSize = $TotalCompressed
            Ratio = "{0:P2}" -f ($TotalCompressed / $TotalSize)
        }
    }
} 
Share on:
comments powered by Disqus