I have a powershell script where I send a call to REST Api:
$DownloadReportResponse = Invoke-RestMethod -Method Post -Uri $DownloadReportUrl -ContentType "application/json" -Body $DownloadReportRequestBody | Out-File -FilePath ("C:\Practice\Report-01_29_14-28.pdf") -Force
The response I get is a binary representation of the pdf, so it is bunch of texts:
>>
endobj
5 0 obj
<<
/N 3
/Length 11 0 R
/Filter /FlateDecode
>>
stream
xwXSçÇßsNö`$!l{¥# ¦Ù¢ $÷#T°¢¨ÈR)X°ZÔ(âÞ
RZ¬âÂÑD§õööÞÛÛïç|ßûû½çý÷y ¤L®0V#(#ü½±qñì `= nn¶WXX0+ÐÍÈ;Ñ« R¼¯1{ÿOªÜl± (Lγxü\®ä/ÉVØ'åLKÎP0R°X~#9k(8u?ûÌ°§yBOÎrÎæ y
îó<)_Î"â<?_Î×ål)
äüF+äsä9 H
The Out-File -FilePath ("C:\Neoload\Report-01_29_14-28.pdf") command will save it as a pdf but when I open it I have no luck seeing the content.
Question: What commands are used to decoding the api response which sends pdf in binary representation and how do I go about saving it in my machine?
This should work:
$DownloadReportResponse = Invoke-RestMethod -Method Post -Uri $DownloadReportUrl -ContentType "application/json" -Body $DownloadReportRequestBody -OutFile "C:\Users\demo\download.pdf"
Documentation Example
Below one is working for me when downloading files from Box.com to local machine:
Invoke-RestMethod -Uri $url -Headers $headers -Method Get -OutFile 'E:\NewfileName.pdf'
instead of
Invoke-RestMethod -Uri $url -Headers $headers -Method Get | Out-File 'E:\NewfileName.pdf'
Mark as Answer if issue resolved.
Related
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:
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)
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))
I am attempting to use Powershell to perform some "POST" requests. However, I can't seem to get the JSON correctly formatted. How do I accomplish this?
>> $JSON=#{name:"TestName"}
>> Invoke-WebRequest -Uri http://localhost:7071/api/HttpTrigger1 -Method POST -Body $JSON
>> $response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" -Method Post -Body $JSON -ContentType "application/json"
ParserError:
Line |
1 | $JSON=#{name:"TestName"}
| ~
| Missing '=' operator after key in hash literal.
So, there are two ways you can do this:
The first, as suggested by Santiago, is
$json = '{name:"TestName"}'
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The second, using (roughly) the syntax you were using, is
#create a Powershell object (note the use of '=' instead of ':' for assignment)
#(such a simple example is not an improvement over the example above)
$json = #{ name = "TestName" } | ConvertTo-JSON
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The first method is certainly cleaner and more direct. The second is useful when the source data for the request comes as the result of manipulating Powershell objects, and you want to convert them for use in a web request.
I'm trying to create a powershell script to access JoeSandBox API to download reports.
I'm following their API details there https://www.joesandbox.com/userguide?sphinxurl=usage/webapi.html
Here's the beginning of the REST script I've put together:
$json = #{
apikey="XXXX";
webid= "YYYY"
} | ConvertTo-Json
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -Body $json -ContentType 'multipart/form-data'
Basically, I don't get the access...
Invoke-RestMethod : {"errors":[{"code":2,"message":"apikey is required."}]}
Thanks
$body = #{'apikey'='XXX'; 'webid'='YYY'}
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -body $body
I want to pass a few body parameters using x-www-form-urlencoded format using powershell invoke-restmethod. Do not that this is working fine in PostMan. My code for this is below but is not working. How do I accomplish this in powershell?
$param = [System.Web.HttpUtility]::UrlEncode("channel:channelID
Content-Type:application/x-www-form-urlencoded
limit:50")
$uri="https://MySlackWebsite.com/api/channels.history"
$test2 = Invoke-RestMethod -Method POST -Uri $uri -Headers $headerJson -Body $param
I got this to work with the following using the guidance I got from #Erik Kalkoken.
$headerJson = #{Authorization="Bearer xoxp-xyz"}
$postParams = #{channel='roomID';limit=50}
$uri="https://slackserver.com/api/channels.history"
Invoke-RestMethod -Method POST -Uri $uri -Headers $headerJson -Body $postParams -ContentType "application/x-www-form-urlencoded"
Here is an example script on how to retrieve the list of messages from a channel with a POST request.
$postParams = #{token='xoxp-XXX';channel='C12345678'}
$test2 = Invoke-WebRequest -Uri https://slack.com/api/channels.history -Method POST -Body $postParams
Write-Host $test2
It tested and based on this answer about how to create a POST request with PowerShell.
I have a VM called "myannoyingVM1 1"
Invoke-RestMethod -Uri $uri -Method Post -Body "vms,vmid=VirtualMachine-vm-
679,vmname=myannoyingvm1 1 cpu=4,memoryGB=8"
When I try to post this to my influxdb I get the below...
Invoke-RestMethod : {"error":"unable to parse 'vms,vmid=VirtualMachine-vm-679,vmname=myannoyingvm1 1 cpu=4,memoryGB=8':
invalid field format"}
Which makes sense, how do I make it realise that it is one tag
After playing around with escape characters for curl on Windows OS I found \ works.
$b = "vms3,vmid=VirtualMachine-vm-679,vmname=myannoyingvm1\ 1 cpu=4,memoryGB=8"
Invoke-RestMethod -Uri $uri -Method Post -Body $b