调用API触发Azure策略按需评估时遇连接关闭错误
解决Azure策略按需评估API调用的连接错误
问题场景
管理8个Azure订阅,通过PowerShell调用API批量触发策略按需评估,执行脚本时出现连接关闭错误,已尝试设置[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12但无效。
执行的脚本
$subscriptions = Get-AzSubscription | Where-Object Name -eq 'xxx' foreach($subscription in $subscriptions){ Set-AzContext -Subscription $subscription $SubscriptionId = $subscription.Id $azContext = Get-AzContext $azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile $profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile) $token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId) $authHeader = @{ 'Content-Type'='application/json' 'Authorization'='Bearer ' + $token.AccessToken } $restUri = "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview" Invoke-RestMethod -Uri $restUrl -Method POST -Headers $authHeader }
报错信息
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive. At line:1 char:1 + Invoke-RestMethod -Uri $restUrl -Method POST -Headers $authHeader + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
解决方案
1. 修正变量拼写错误
脚本中定义了$restUri存储API地址,但调用Invoke-RestMethod时误用了$restUrl(大小写不一致),导致请求指向无效地址,这是引发连接错误的核心原因。
2. 简化认证流程
使用Azure PowerShell内置的Get-AzAccessToken cmdlet获取token,替代手动实例化RMProfileClient的复杂逻辑,减少出错概率:
$token = Get-AzAccessToken -ResourceUrl "https://management.azure.com/" $authHeader = @{ 'Content-Type'='application/json' 'Authorization'="Bearer $($token.Token)" }
3. 增加错误处理与日志
在循环中加入try/catch块,输出当前订阅ID和错误详情,便于定位问题。
修正后的完整脚本
# 强制使用TLS1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $subscriptions = Get-AzSubscription | Where-Object Name -eq 'xxx' foreach($subscription in $subscriptions){ try { Set-AzContext -Subscription $subscription | Out-Null $subscriptionId = $subscription.Id Write-Host "正在处理订阅: $subscriptionId" # 获取访问令牌 $token = Get-AzAccessToken -ResourceUrl "https://management.azure.com/" $authHeader = @{ 'Content-Type'='application/json' 'Authorization'="Bearer $($token.Token)" } $restUri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview" $response = Invoke-RestMethod -Uri $restUri -Method POST -Headers $authHeader Write-Host "订阅 $subscriptionId 触发评估成功,响应: $($response | ConvertTo-Json -Compress)" } catch { Write-Error "订阅 $($subscription.Id) 处理失败: $_" } }
内容的提问来源于stack exchange,提问作者learner
相关产品推荐
相关产品推荐

