I need to compress a string to Zlib in PowerShell.
Is there a way we can compress using the ZLibStream class in PowerShell?
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zlibstream?view=net-8.0
I was able to compress using the class DeflateStream and GZipStream, but the external system which uses the data was not able to decode it.
This is the powershell script I tried with
$stringToCompress = 'string to compress'
$memStream = New-Object System.IO.MemoryStream
$deflateStream = New-Object System.IO.Compression.GZipStream($memStream, [System.IO.Compression.CompressionMode]::Compress)
$streamWriter = New-Object System.IO.StreamWriter($deflateStream)
$streamWriter.Write($stringToCompress)
$streamWriter.Close();
$encodedCompressedString = [System.Convert]::ToBase64String($memStream.ToArray())
Write-Output $encodedCompressedString
The process of compression and expansion with
ZLibStreamis pretty much the same as withGZipStream.Note that
ZlibStreamonly works with .NET 6+ meaning that it is not available for Windows PowerShell 5.1 (.NET Framework 4.5+). If you want to use this class you will need to install PowerShell 7+.An alternative for Windows PowerShell 5.1 can be to use the
ZLibWrapperpackage.First download the package and expand it:
Then the flow is pretty similar using their assembly: