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

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

你的脚本在我这边工作得很好。这个问题似乎与您的客户机机器环境有关。你可以查看这个博客,看看这个解决方案是否对你有帮助:

问题是旧版本的DOTNET框架(即3.5和4.0)本质上不支持新版本的TLS,如1.2和1.3。您可以尝试安装较新版本的DOTNET。微软关于SSL/TLS的更多信息可以在这里找到:

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

我最近解决了Windows server 2022中PowerShell的类似问题。

在我的例子中,它是由一个实际运行脚本的用户的代理被关闭引起的。

请注意,我没有调用外部站点,因为我从PowerShell调用的站点托管在同一台服务器的IIS中,但是PowerShell命令仍然需要打开代理。

打开代理:打开Internet Explorer浏览器>设置符号>"互联网Options"比;"Connections"选项卡在"局域网settings">

标记下面两个复选框,并输入有效的代理和端口。

请注意,这些选项是基于每个用户的-如果您为一个系统帐户设置了它,另一个系统帐户可能没有配置它。

代理设置

最新更新