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

PowerShell脚本求助:获取带PROD标签的Windows VM时订阅列空、过滤失效

问题分析与修正脚本

问题原因说明

  1. Subscription列为空:Get-AzResourceGroup返回的对象不存在Subscription属性,原脚本中$group.Subscription无法取到有效内容;同时原脚本未遍历租户内所有订阅,仅处理当前激活的订阅。
  2. 标签过滤规则未生效:原脚本虽然过滤出了带目标标签的资源组,但获取VM时未指定资源组参数,导致获取了当前订阅下所有VM,完全忽略了之前的资源组过滤条件。

修正后的脚本

# 获取租户内所有订阅
$subscriptions = Get-AzSubscription

# 初始化结果数组
$results = @()

# 遍历每个订阅
foreach ($sub in $subscriptions) {
    # 切换到当前订阅
    Select-AzSubscription -SubscriptionObject $sub | Out-Null

    # 获取当前订阅中,标签ApplicationName包含PROD的资源组
    $resourceGroups = Get-AzResourceGroup | Where-Object { 
        $null -ne $_.Tags -and $_.Tags['ApplicationName'] -like "*PROD*" 
    }

    # 遍历每个符合条件的资源组
    foreach ($group in $resourceGroups) {
        $groupName = $group.ResourceGroupName
        # 获取当前资源组内的所有VM
        $vms = Get-AzVM -ResourceGroupName $groupName

        # 筛选Windows系统的VM
        foreach ($vm in $vms) {
            if ($vm.StorageProfile.OSDisk.OSType -eq "Windows") {
                $result = [ordered]@{
                    'VM Name'        = $vm.Name
                    'Subscription'   = $sub.Name  # 使用当前订阅的名称
                    'Resource Group' = $groupName
                    'Location'       = $vm.Location
                    'Publisher'      = $vm.StorageProfile.ImageReference.Publisher
                    'Plan'           = $vm.StorageProfile.ImageReference.Sku
                    'Offer'          = $vm.StorageProfile.ImageReference.Offer
                }
                $results += New-Object -TypeName PSObject -Property $result
            }
        }
    }
}

# 输出表格结果
$results | Format-Table -AutoSize

# 导出到CSV文件(请替换为你的目标路径)
$results | Export-Csv -Path "C:\Users\XXXXXXXXXX\WindowsVMsList.csv" -NoTypeInformation

Write-Output "脚本执行完成。"

额外优化说明

如果你的需求是VM自身的标签包含PROD,而非资源组的标签,可将资源组过滤的逻辑替换为直接筛选VM的标签:

# 在订阅遍历内,直接获取带目标标签的Windows VM
$vms = Get-AzVM | Where-Object {
    $null -ne $_.Tags -and $_.Tags['ApplicationName'] -like "*PROD*" -and
    $_.StorageProfile.OSDisk.OSType -eq "Windows"
}

这种情况下可以去掉资源组遍历的逻辑,直接收集符合条件的VM即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:15:15