1

I am trying to process a multipart GET call in powershell and then save the zipfile it contains to disk. I can execute this:

$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers

and then echo out the filename and contents. In order to save the file, I tried this:

$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "multipart/form-data" -Outfile result.zip

This raises an error (Invalid Operation). So I tried this:

$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers -ContentType "application/zip" -Outfile result.zip

This creates a file called result.zip which isn't valid. I know that the response is multipart, so while this doesn't raise an error, I am not surprised that the file is invalid because it must contain all of the parts.

I have looked around, but all I find are ways of using Invoke-RestMethod to POST mulitpart content.

This is the error when I try to open the resulting zip file:

enter image description here

I have also tried to decode the result as below, but with the same results.

$B64String = $response.resultObject 
Write-Host "resultObject size: $([Math]::Round($B64String.Length / 1Mb,2)) MiB"
$swDecode = [System.Diagnostics.Stopwatch]::StartNew()
$bytes = [System.Convert]::FromBase64String($B64String)
$swDecode.Stop()
Write-Host "Decoded size: $([Math]::Round($bytes.Count / 1Mb,2)) MiB"
Write-Output $bytes > $($response.fileName)
4
  • "This creates a file called result.zip which isn't valid" - can you expand on this? result.zip is a perfectly valid file name in any filesystem I can think of... Commented Jan 20, 2022 at 17:41
  • I will add more details. Commented Jan 21, 2022 at 15:21
  • Ahh, you mean the resulting file contents are invalid/corrupt, that makes more sense :) Try using Invoke-WebRequest -OutFile ... instead of Invoke-RestMethod -OutFile Commented Jan 21, 2022 at 15:24
  • I don't think the contents are corrupt, I just think that I have not processed them correctly. If I convert the response into JSON, there are three fields: id, fileName, and resultObjet. Using --OutFile does not work because the file will include id and fileName. But also just using resultObject doesn't work either. My question is how should I be encoding/decoding resultObject Commented Jan 21, 2022 at 16:10

1 Answer 1

1

I found the answer

$response = Invoke-RestMethod -Uri $reqUrl -Method Get -Headers $headers  
$response | ConvertTo-Json
[IO.File]::WriteAllBytes($response.fileName, [System.Convert]::FromBase64String($response.resultObject))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.