0

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

2 Answers2

2

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"
0

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.

Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114
  • Hey Erik, that part works fine. Please note that I have gotten this to work in post man. The issue that I'm having with is in powershell where converting header params to application/x-www-form-urlencoded is not working, causing my invoke rest method requests to fail. – JackleTackle Apr 24 '19 at 15:52
  • This example is posting as `application/x-www-form-urlencoded`. Which params exactly are not working for you? – Erik Kalkoken Apr 24 '19 at 15:54
  • This is the code that I'm testing with: $req = [System.Web.HttpUtility]::UrlEncode("channel:ChangelID Content-Type:application/x-www-form-urlencoded limit:50") $uri="https://slackserver.com/api/channels.history" $test2 = Invoke-RestMethod -Method POST -Uri $uri -Headers $headerJson -Body $req -ContentType "application/x-www-form-urlencoded" – JackleTackle Apr 24 '19 at 16:09
  • ok, but why do you not just use the code I posted? It does exactly what you are asking I think – Erik Kalkoken Apr 24 '19 at 16:33