Created
November 11, 2019 11:35
-
-
Save purplemonkeymad/7f669507e22397160915f6e3a729bc05 to your computer and use it in GitHub Desktop.
Text file compression cmdlets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function ConvertTo-DeflateBase64String{ | |
| [cmdletbinding(DefaultParameterSetName="String")] | |
| Param( | |
| [Parameter(ParameterSetName="String",Mandatory=$true,ValueFromPipeline=$true,Position=1)][string]$String, | |
| [Parameter(ParameterSetName="Byte",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=2)] | |
| [Byte[]]$Bytes | |
| ) | |
| process{ | |
| $ms = New-Object System.IO.MemoryStream | |
| $cwr = New-Object System.IO.Compression.DeflateStream($ms,[System.IO.Compression.CompressionMode]::Compress) | |
| $sw = New-Object System.IO.StreamWriter($cwr) | |
| switch ($PSCmdlet.ParameterSetName) { | |
| "String" { $sw.Write($String) } | |
| "Byte" { $sw.Write( [char[]]$Bytes) } | |
| Default { Write-Error "Unknown input format $_"; return} | |
| } | |
| $sw.close() | |
| $compressedBytes = $ms.ToArray() | |
| $ret = [System.Convert]::ToBase64String($compressedBytes) | |
| return $ret | |
| } | |
| } | |
| function ConvertFrom-DeflateBase64String{ | |
| Param( | |
| [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=1)][string]$String, | |
| [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=2)] | |
| [ValidateSet('String','Byte')][String]$OutputFormat = 'String' | |
| ) | |
| process{ | |
| $data = [System.Convert]::FromBase64String($String) | |
| $ms = New-Object System.IO.MemoryStream | |
| $ms.Write($data,0,$data.length) | |
| [void]$ms.Seek(0,0) | |
| $cwr = New-Object System.IO.Compression.DeflateStream($ms,[System.IO.Compression.CompressionMode]::Decompress) | |
| $sr = New-Object System.IO.StreamReader($cwr) | |
| switch ($OutputFormat) { | |
| 'String' { | |
| $ret = $sr.ReadToEnd() | |
| return $ret | |
| } | |
| 'Byte' { | |
| $ReturnBytes = while ($sr.Peek() -gt -1) { | |
| [byte]$sr.Read() | |
| } | |
| return $ReturnBytes | |
| } | |
| Default { Write-Error "Unknown output format $_"; return} | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment