Gzip compression and BASE64 encoding in Powershell
I found an excellent way of compressing and encoding files in powershell. Say that you have a large UTF-16 file, that needs to be transferred over the internet, and you need to automate that transfer.
Important
|
Antivirus heuristic scan will probably detect this, as it is a typical way of transferring malicious code, so be sure to sign your script and make en exception in your antivirus solution for your code signing cert. |
The code
encode.ps1
$s = @"
....
error: The requested operation returned error: 1954 Forbidden search for defensive operations manual
absolutely fatal: operation initiation lost in the dodecahedron of doom
would you like to die again? y/n
....
"@
$ms = New-Object System.IO.MemoryStream
$cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress)
$sw = New-Object System.IO.StreamWriter($cs)
$sw.Write($s)
$sw.Close();
$s = [System.Convert]::ToBase64String($ms.ToArray())
write-host $s
decode.ps1
#PSGzip decompression
$data = [System.Convert]::FromBase64String($s)
$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.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))
$string = $sr.ReadToEnd()
write-host $string