You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动获取连接名并查询多资源组中多个VNet网关连接状态?

批量查询多资源组VNet网关连接状态方案

核心思路

无需手动获取连接名,通过PowerShell批量遍历指定资源组的虚拟网络网关,自动关联其对应的连接资源,最终输出连接状态等关键信息。

可直接运行的PowerShell脚本

情况1:查询指定资源组列表

# 定义需要查询的资源组(按需修改)
$targetResourceGroups = @("rg1", "rg2")

# 遍历每个目标资源组
foreach ($rg in $targetResourceGroups) {
    # 获取当前资源组下所有虚拟网络网关
    $virtualNetworkGateways = Get-AzVirtualNetworkGateway -ResourceGroupName $rg
    
    if ($virtualNetworkGateways) {
        Write-Host "`n=== 资源组 [$rg] 网关连接状态 ===" -ForegroundColor Cyan
        
        # 遍历每个网关,匹配关联的连接
        foreach ($gateway in $virtualNetworkGateways) {
            # 获取当前资源组下所有网关连接,并筛选与当前网关关联的项
            $relatedConnections = Get-AzVirtualNetworkGatewayConnection -ResourceGroupName $rg | 
                Where-Object {
                    $_.VirtualNetworkGateway1.Id -eq $gateway.Id -or $_.VirtualNetworkGateway2.Id -eq $gateway.Id
                }
            
            if ($relatedConnections) {
                # 格式化输出连接详情
                foreach ($conn in $relatedConnections) {
                    [PSCustomObject]@{
                        资源组名          = $rg
                        本地网关名        = $gateway.Name
                        连接名            = $conn.Name
                        连接状态          = $conn.ConnectionStatus
                        连接类型          = $conn.ConnectionType
                        对等网关资源组    = if ($conn.VirtualNetworkGateway1.Id -eq $gateway.Id) {
                            ($conn.VirtualNetworkGateway2.Id -split "/")[4]
                        } else {
                            ($conn.VirtualNetworkGateway1.Id -split "/")[4]
                        }
                        对等网关名        = if ($conn.VirtualNetworkGateway1.Id -eq $gateway.Id) {
                            ($conn.VirtualNetworkGateway2.Id -split "/")[-1]
                        } else {
                            ($conn.VirtualNetworkGateway1.Id -split "/")[-1]
                        }
                    }
                }
            } else {
                Write-Host "网关 [$($gateway.Name)] 未配置任何连接" -ForegroundColor Yellow
            }
        }
    } else {
        Write-Host "资源组 [$rg] 未找到虚拟网络网关" -ForegroundColor Yellow
    }
}

情况2:查询当前订阅下所有资源组

只需将上述脚本中的$targetResourceGroups替换为以下内容:

# 获取当前订阅下所有资源组
$targetResourceGroups = Get-AzResourceGroup | Select-Object -ExpandProperty ResourceGroupName

额外说明

  • 前置准备:确保已安装Az.Network模块,未安装则执行:Install-Module -Name Az.Network -Force -AllowClobber
  • 登录认证:运行脚本前先登录Azure账号:Connect-AzAccount;多订阅环境需切换目标订阅:Set-AzContext -SubscriptionId "<你的订阅ID>"
  • 结果导出:如需将结果保存为CSV文件,可在输出对象的代码块后追加:| Export-Csv -Path "VNet网关连接状态.csv" -Encoding UTF8 -NoTypeInformation

内容的提问来源于stack exchange,提问作者Phaneendra Allamraju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:24:47