Search code examples
powershellrestcurldynamics-crmbearer-token

Rest API call works with curl but doesn't work with PowerShell


I have following curl request that works

curl.exe -X GET "https://host.crm.dynamics.com/api/data/v9.1/accounts?$select=name" -H "Authorization: Bearer xxxxx"

And want to implement it in PowerShell

Invoke-RestMethod "https://host.crm.dynamics.com/api/data/v9.1/accounts?`$select=name" `
                    -Headers @{Authorization = "Bearer xxxxx"} `
                    -Method  Get

I've also tried to do request with Invoke-WebRequest as well as curl version in Powershell and it didn't work

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At E:\Repos\myrepo\host\connection_test.ps1:51 char:1
+ Invoke-RestMethod $hostName `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Solution

  • When making connection using Invoke-RestMethod, you want to make sure that encryption your client is using is accepted by the URI.

    PowerShell by default uses TLS 1.0 for web requests but the URI you are connecting to probably uses 1.1 or 1.2. You can use the following to force the use of TLS v1.1 or v1.2.

    [Net.ServicePointManager]::SecurityProtocol = `
        [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12;
    Invoke-RestMethod "https://host.crm.dynamics.com/api/data/v9.1/accounts?`$select=name" `
                    -Headers @{Authorization = "Bearer xxxxx"} `
                    -Method  Get