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
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 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 tried many ways of uploading a CSV file to ServiceNow using PowerShell via Invoke-RestMethod and Invoke-WebRequest; however, I have hit a wall. When I call the functions, I receive the following error:
"Invoke-RestMethod : The remote server returned an error: (405) Method Not Allowed."
"Invoke-WebRequest : The remote server returned an error: (405) Method Not Allowed."
I have tried the code below:
Attempt 1)
$Headers = #{'Auth_token'=$envCred};
$FileContent = [IO.File]::ReadAllText('C:\temp\test.csv');
$Fields = #{'uploadFile'=$FileContent};
Invoke-WebRequest -Uri $Uri -ContentType 'multipart/form-data' -Method Post -Headers $Headers -Body $Fields;
Attempt 2)
Invoke-RestMethod -Method Post -Uri $uri -Credential $envCred -ContentType 'multipart/form-data -InFile "C:\temp\test.csv" '
I know for a fact that the API is working, because after I call:
Invoke-RestMethod -Method 'get' -Uri $uri -Credential $snCred -body $body it returns the proper information.
I also tried the [-Method Patch] with the following: "Invoke-RestMethod -Uri $uri -Credential $snCred -Method Patch -ContentType 'text/csv' -InFile "C:\temp\test.csv" - Also tried with the -ContentType 'multipart/form-data' - I get the following error: "Invoke-RestMethod : The remote server returned an error: (415) Unsupported Media Type."
Is there another way or uploading CSV file(s) in PowerShell using the Invoke-RestMethod or Invoke-WebRequest?
Solution:
I realized that I had a typo with my URI, after fixing it, it worked! Sorry for the inconvenience.
It's unclear what endpoint you were using, however, here's an example from the docs
curl "https://instance.service-now.com/api/now/attachment/upload" \
--request POST \
--header "Accept:application/json"
--user 'admin':'admin'"\
--header "Content-Type:multipart/form-data"
-F 'table_name=incident' -F 'table_sys_id=d71f7935c0a8016700802b64c67c11c6' -F 'encryption_context=undefined'-F 'uploadFile=# location of the file on file system'
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.