Rest API 调用适用于 curl 但不适用于 PowerShell

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

我有以下 curl 有效的请求

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

并想在 PowerShell 中实现它

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

我也尝试在 Powershell 中使用 Invoke-WebRequestcurl 版本发出请求,但没有成功

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

使用 Invoke-RestMethod 建立连接时,您需要确保 URI 接受您的客户端使用的加密。

默认情况下,PowerShell 使用 TLS 1.0 进行 Web 请求,但您要连接的 URI 可能使用 1.1 或 1.2。您可以使用以下命令强制使用 TLS v1.1 或 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