Skip to content

Instantly share code, notes, and snippets.

@vortexau
Last active October 24, 2024 19:35
Show Gist options
  • Save vortexau/13de5b6f9e46cf419f1540753c573206 to your computer and use it in GitHub Desktop.
Save vortexau/13de5b6f9e46cf419f1540753c573206 to your computer and use it in GitHub Desktop.
Powershell to decompress DEFLATE data
$base64data = "insert compressed and base64 data here"
$data = [System.Convert]::FromBase64String($base64data)
$ms = New-Object System.IO.MemoryStream
$ms.Write($data, 0, $data.Length)
$ms.Seek(0,0) | Out-Null
$sr = New-Object System.IO.StreamReader(New-Object System.IO.Compression.DeflateStream($ms, [System.IO.Compression.CompressionMode]::Decompress))
while ($line = $sr.ReadLine()) {
$line
}
@kevXZY
Copy link

kevXZY commented Oct 27, 2022

Thanks @Luiz-Monad , this helped me a lot !

@pzarczyn
Copy link

Why this script return error, like below?

Exception calling "ReadLine" with "0" argument(s): "Block length does not match with its complement."

What format of data should I use or how to get sample data? I tried to create taht sample, using the extension in Chrome "Zlib Compressor" and getting that error like above.
I'm using powershell 5x
Thanks for help

@Luiz-Monad
Copy link

Why this script return error, like below?

Exception calling "ReadLine" with "0" argument(s): "Block length does not match with its complement."

What format of data should I use or how to get sample data? I tried to create taht sample, using the extension in Chrome "Zlib Compressor" and getting that error like above. I'm using powershell 5x Thanks for help

That's because you're trying to decompress data compressed in another format like gzip or not compressed.
This is how you use it

# create the stream

$data1 = "this is what goes`nanother line"
$data2 = "more lines"

$msw = New-Object System.IO.MemoryStream
$sw = New-Object System.IO.StreamWriter(New-Object System.IO.Compression.DeflateStream($msw, [System.IO.Compression.CompressionMode]::Compress))
$sw.WriteLine($data1)
$sw.Write($data2)
$sw.Close()

# this is binary compressed data
$data = $msw.ToArray()

# deflate the stream
$ms = New-Object System.IO.MemoryStream
$ms.Write($data, 0, $data.Length)
$ms.Seek(0,0) | Out-Null

$sr = New-Object System.IO.StreamReader(New-Object System.IO.Compression.DeflateStream($ms, [System.IO.Compression.CompressionMode]::Decompress))

while ($line = $sr.ReadLine()) {  
    $line
}
#outputs
# this is what goes
# another line
# more lines

@Luiz-Monad
Copy link

also, if you are trying to decompress things compressed by zlib, you probably want to use ZLibStream instead of DeflateStream. Now, if you're trying to decompress an actual ZipFile, the process is different, those are for bare streams.

@pzarczyn
Copy link

Thank you @Luiz-Monad, this helped me a lot and works now.
Have a great day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment