22

This curl command works as desired:

curl -H "X-Api-Key:j65k423lj4k2l3fds" `
     -X PUT `
     -d "alerts_enabled=true" `
        https://some/working/file.xml

How can I recreate this natively in PS with Invoke-WebRequest? I've tried

Invoke-WebRequest -Headers @{"X-Api-Key" = "j65k423lj4k2l3fds"} `
                  -Method PUT `
                  -Body "alerts_enabled=true" `
                  -Uri https://some/working/file.xml

I've also tried making objects for all the params (e.g. $headers = @{"X-Api-Key" = "Key:j65k423lj4k2l3fds"} and passing -Headers $headers).

Thanks

slugster
  • 49,403
  • 14
  • 95
  • 145
user3561945
  • 441
  • 1
  • 3
  • 9

3 Answers3

26

Try adding the parameter -ContentType e.g.:

Invoke-WebRequest -Headers @{"X-Api-Key" = "j65k423lj4k2l3fds"} -Method PUT `
                  -Body "alerts_enabled=true" -Uri https://some/working/file.xml `
                  -ContentType application/x-www-form-urlencoded

That results in a request that looks like this (from Fiddler):

PUT http://some/working/file.xml HTTP/1.1
X-Api-Key: j65k423lj4k2l3fds
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.2; en-US) WindowsPowerShell/5.0.9701.0
Content-Type: application/x-www-form-urlencoded
Host: some
Content-Length: 19
Expect: 100-continue

alerts_enabled=true

For testing, I changed the URL from https to http. If that doesn't work, go download Fiddler and inspect the RAW request when curl is used to see what is different.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • When are quotes needed - as in the `body` and when not as in `-uri`? My curl I want to convert to ps starts with `curl -s -k -m 5` so I have to find out the flag names as methods in `ps`. As body - `-d` - I have a xml file, maybe I can put that in another file to have it well formatted. – Timo Jun 22 '21 at 18:46
12

got it to work natively using invoke-webrequest. powershell guru here at work helped me out. Switched to the New Relic API version 2 (available at https://rpm.newrelic.com/api/explore), which uses JSON instead of xml, and made some sytax tweaks.

$json = @"{"alert_policy":[{"enabled":"true"}]"@

$headers = @{}
$headers["X-Api-Key"] = "j65k423lj4k2l3fds"

Invoke-WebRequest -Uri "https://some/working/file.json" -Body $json -ContentType "application/json" -Headers $headers -Method Post
user3561945
  • 441
  • 1
  • 3
  • 9
  • 1
    although the code above was producing a 200, and some response json, it was not toggling the setting in New Relic. I was POSTing instead of PUTing...so pay attention to that. – user3561945 May 13 '14 at 12:27
5

This works for me in Powershell using the curl alias to Invoke-WebRequest...

 curl -H @{"X-Api-Key" = "j65k423lj4k2l3fds"} -Method PUT 'https://some/working/file.xml'
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173