2

I'm having issues converting a curl command into Powershell Invoke-RestMethod. Ihave tried a number of different ways but i get error message: Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

The curl command that i need to convert for powershell:

curl -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" https://api.vasttrafik.se:443/token

What i have tried so far:

$token = "c0a6dcae-e14b-3255-88a9-c83df513b314"
$headers = @{Authorization = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("sometoken1234567890"))}
$body = ConvertTo-Json @{"grant_type" = "client_credentials"}


Invoke-RestMethod -Method Post -Headers $headers -Body $body -Uri "https://api.vasttrafik.se:443/token"

Also:

$body = @{
grant_type = "client_credentials"
}

$headers = @{
Authorization = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("sometoken1234567890"))
Accept = "application/json"
ContentType = "application/json"
}

$params = @{
Method = "Post"
Uri = "https://api.vasttrafik.se:443/token"
Body = $body

Header = $headers
}

Invoke-RestMethod @params

I get the same error for both of them

I would be very much appreciated if someone could help

zyntrax
  • 88
  • 9
  • 2
    curl.exe ships with Windows 10+ these days so often you don't need that conversion... – Daniel Stenberg Nov 25 '21 at 08:30
  • When i try to run below directly in powershell: curl -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" https://api.vasttrafik.se:443/token I get: Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Authorization: Basic sometoken1234567890" value of type "System. String" to type "System.Collections.IDictionary". – zyntrax Nov 25 '21 at 08:37
  • 1
    use `curl.exe` to avoid the silly alias to trip you – Daniel Stenberg Nov 25 '21 at 08:45
  • Thank you, managed to get it working by running the following: $curl = curl.exe -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" https://api.vasttrafik.se:443/token | ConvertFrom-Json $curl.expires_in $curl.access_token Now i can finally move on :) – zyntrax Nov 25 '21 at 08:49

1 Answers1

1

Thanks to Daniel Stenberg i managed to get it working by running the below code:

$curl = curl.exe -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" api.vasttrafik.se:443/token | ConvertFrom-Json 

$curl.expires_in 
$curl.access_token
zyntrax
  • 88
  • 9