Invoke-RestMethod:底层连接已关闭 powershell 脚本中的错误

Invoke-RestMethod : The underlying connection was closed error in powershell script

我曾在 PowerShell 中编写代码,通过 wiql 获取项目某个区域的工作项。

$token = "PAT"

$url="https://dev.azure.com/Organizationname/_apis/wit/wiql?api-version=5.1"

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))

$JSON = @'
{
   "query": "SELECT [System.Id], [System.WorkItemType],  [System.State],[System.AreaPath],[System.Tags],[System.CommentCount],[System.ChangedDate] FROM workitems WHERE[System.Id] IN(@follows) AND [System.TeamProject] = 'Azure' AND [System.State] <> '' ORDER BY [System.ChangedDate] DESC"
}
'@

$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json

$listOfTasks = New-Object Collections.Generic.List[String]
ForEach( $workitem in $response.workItems ) {
  $listOfTasks.Add($workitem.id)

}
$listOfTasks = $listOfTasks -join ','
$listOfTasks

$url1="https://dev.azure.com/Organizationname/ProjectName/_apis/wit/workitems?ids=$listOfTasks" +"&" + "`$expand" + "=all&api-version=5.1"

$response1 = Invoke-RestMethod -Uri $url1 -Headers @{Authorization = "Basic $token"} -Method Get 

Write-Host "result = $($response1 | ConvertTo-Json -Depth 100)"

当我执行 aboce 脚本时出现以下错误。

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
At ....
+ ... response1 = Invoke-RestMethod -Uri $url1 -Headers @{Authorization = " ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我已经尝试了下面提到的选项link,但没有帮助。

https://blog.darrenjrobinson.com/powershell-the-underlying-connection-was-closed-an-unexpected-error-occurred-on-a-send/

有人可以帮我解决这个错误吗? 在此先多谢!!!

这通常是由于您的 TLS 版本。

尝试添加:

​[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

到脚本的顶部并重新运行它。

你的脚本对我来说效果很好。看来问题与您的客户端计算机环境有关。您可以检查 this blog 以查看该解决方案是否对您有帮助:

问题是旧版本的 DOTNET 框架(即 3.5 和 4.0)本身并不支持新版本的 TLS,如 1.2 和 1.3。您可以尝试安装较新版本的 DOTNET。有关 SSL/TLS 的更多信息,请参见此处:

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls