I am writing a PowerShell function/script (using the version that ships with Windows 10, which I believe is 5.0) to take in a GZip compressed Base64 string and decompress it, and then decode it under the assumption the original uncompressed/decoded string was Unicode encoded.
I am trying to instantiate a new object instance of type MemoryStream using this constructor and the New-Object cmdlet. It takes one parameter, which is an array of bytes.
PowerShell is unable to find a valid overload that accepts the array of bytes I am trying to pass as the constructor's parameter. I believe the issue is due to the array's relatively large length. Please see my code below:
Function DecompressString()
{
param([parameter(Mandatory)][string]$TextToDecompress)
try
{
$bytes = [Convert]::FromBase64String($TextToDecompress)
$srcStreamParameters = @{
TypeName = 'System.IO.MemoryStream'
ArgumentList = ([byte[]]$bytes)
}
$srcStream = New-Object @srcStreamParameters
$dstStream = New-Object -TypeName System.IO.MemoryStream
$gzipParameters = @{
TypeName = 'System.IO.Compression.GZipStream'
ArgumentList = ([System.IO.Stream]$srcStream, [System.IO.Compression.CompressionMode]::Decompress)
}
$gzip = New-Object @gzipParameters
$gzip.CopyTo($dstStream)
$output = [Text.Encoding]::Unicode.GetString($dstStream.ToArray())
Write-Output $output
}
catch
{
Write-Host "$_" -ForegroundColor Red
}
finally
{
if ($gzip -ne $null) { $gzip.Dispose() }
if ($srcStream -ne $null) { $srcStream.Dispose() }
if ($dstStream -ne $null) { $dstStream.Dispose() }
}
}
DecompressString
$ExitPrompt = Read-Host -Prompt 'Press Enter to Exit'
The error message I get is: Cannot find an overload for "MemoryStream" and the argument count: "1764".
Can anyone please clarify how I can get the script interpreter to use the constructor correctly with a large byte array?
$bytes, which apparently is of length 1764, as a separate argument to aMemoryStreamconstructor but no such overload exists. You need to wrap$bytesin an array like this:,([byte[]]$bytes)(note the leading comma).$srcStream = [System.IO.MemoryStream]::new([byte[]]$bytes)instead?New-Objectstatements for[typename]::new(..). Faster and more efficient.