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

问题描述

我在 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

我尝试了以下链接中提到的选项,但没有帮助。

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。可以在此处找到 Microsoft 有关 SSL/TLS 的更多信息:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...