Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to recreate a working CURL command with Invoke-WebRequest in Powershell

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

like image 976
user3561945 Avatar asked May 08 '14 21:05

user3561945


People also ask

Does invoke-WebRequest use curl?

curl in PowerShell uses Invoke-WebRequest . From PowerShell 3.0 and above, you can use Invoke-WebRequest , which is equivalent to curl .

How do I run a curl command in Windows PowerShell?

The conclusion is that if you need to use the curl (as same as in the Windows command prompt) in PowerShell then you need to call the curl executable( curl.exe ) directly. Else, you should stick to the PowerShell curl alias which resolves to the Invoke-WebRequest cmdlet under the hood.

What is invoke-WebRequest in PowerShell?

Description. The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements. This cmdlet was introduced in Windows PowerShell 3.0.

Does invoke-WebRequest use proxy?

Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables.


1 Answers

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.

like image 124
Keith Hill Avatar answered Sep 25 '22 12:09

Keith Hill