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

获取Az虚拟网络网关扩展属性及资源名称异常问题

解决Azure虚拟网络网关名称获取异常的问题

问题说明

编写PowerShell脚本收集Azure虚拟网络网关信息时,发现获取的Name字段是网关IP配置的名称(对应截图红箭头指向内容),而非网关资源本身的名称(黄箭头目标内容)。

问题根源

脚本中使用了-ExpandProperty IpConfigurations参数,该参数会将IpConfigurations的属性展开到顶层对象,导致网关自身的Name属性被IP配置的Name覆盖,因此读取$gateway.Name时得到的是IP配置的名称,而非网关资源名称。

修正后的脚本

$gatewayDetailsArray = @()

# 遍历所有订阅
foreach ($subscription in $subscriptions) {
    Write-Host "Processing Subscription: $($subscription.Name)" -ForegroundColor Yellow

    # 切换到当前订阅
    Select-AzSubscription -SubscriptionId $subscription.Id

    # 获取当前订阅下的所有资源组
    $resourceGroups = Get-AzResourceGroup

    # 遍历每个资源组获取虚拟网络网关
    foreach ($resourceGroup in $resourceGroups) {
        # 移除-ExpandProperty IpConfigurations,避免覆盖网关自身属性
        $gateways = Get-AzVirtualNetworkGateway -ResourceGroupName $resourceGroup.ResourceGroupName | 
                    Select-Object -Property Name, GatewayType, VpnType, Sku, IpConfigurations, ResourceGroupName

        # 遍历每个网关,收集详细信息
        foreach ($gateway in $gateways) {
            # 从IpConfigurations中提取公网IP资源名称
            $publicIpName = $gateway.IpConfigurations[0].PublicIpAddress.Id -split '/' | Select-Object -Last 1
            # 若需获取实际IP地址,取消以下两行注释
            # $publicIp = Get-AzPublicIpAddress -ResourceGroupName $resourceGroup.ResourceGroupName -Name $publicIpName
            # $gatewayIpValue = $publicIp.IpAddress

            $details = @{
                Subscription = $subscription.Name
                ResourceGroupName = $gateway.ResourceGroupName
                # 现在$gateway.Name为网关资源本身的名称
                Name = $gateway.Name
                GatewayType = $gateway.GatewayType
                VpnType = $gateway.VpnType
                # 若用实际IP地址,替换为$gatewayIpValue
                GatewayIP = $publicIpName
                SKU = $gateway.Sku.Name
                VNET = ($gateway.IpConfigurations[0].Subnet.Id -split '/')[-3]
            }
            $gatewayDetailsArray += New-Object PSObject -Property $details
        }
    }
}

# 导出到CSV文件
$csvFilePath2 = "C:\temp\GatewayDetails_2.csv"
$gatewayDetailsArray | Export-Csv -Path $csvFilePath2 -NoTypeInformation

关键修正点

  • 移除-ExpandProperty IpConfigurations参数,保留网关自身的Name属性不被覆盖。
  • 通过IpConfigurations数组单独提取IP相关信息,避免与网关顶层属性冲突。
  • 若需要获取网关的实际公网IP地址,需额外调用Get-AzPublicIpAddress获取对应资源的IP值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:05:56