Mark Chassy
Mark Chassy

Reputation: 159

Using powershell Invoke-RestMethod to GET multipart content

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)

Upvotes: 1

Views: 1162

Answers (1)

Mark Chassy
Mark Chassy

Reputation: 159

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))

Upvotes: 1

Related Questions