基于Azure管理组名称统计虚拟机(VM)数量的PowerShell脚本需求
解决方案
优先方案:PowerShell脚本
这个脚本会连接Azure账户,遍历所有订阅,获取虚拟机并关联其所属管理组,最终输出三类统计数据。你需要将$targetMgmtGroupKeyword替换为你要匹配的特定字符串。
# 连接Azure账户 Connect-AzAccount # 设置管理组名称匹配关键词 $targetMgmtGroupKeyword = "YourSpecificString" # 获取所有订阅 $subscriptions = Get-AzSubscription # 初始化计数器 $totalVMs = 0 $vmInTargetMgmtGroups = 0 $vmInOtherMgmtGroups = 0 foreach ($sub in $subscriptions) { # 切换到当前订阅 Set-AzContext -Subscription $sub.Id | Out-Null # 获取当前订阅所属的管理组 $mgmtGroups = Get-AzManagementGroupSubscription -SubscriptionId $sub.Id $subMgmtGroupName = $mgmtGroups.Name # 获取当前订阅内的所有虚拟机 $vms = Get-AzVM # 累加总VM数 $totalVMs += $vms.Count # 根据管理组名称匹配情况统计VM数 if ($subMgmtGroupName -like "*$targetMgmtGroupKeyword*") { $vmInTargetMgmtGroups += $vms.Count } else { $vmInOtherMgmtGroups += $vms.Count } } # 输出统计结果 Write-Host "所有Azure订阅的VM总数: $totalVMs" Write-Host "名称包含'$targetMgmtGroupKeyword'的管理组内VM数量: $vmInTargetMgmtGroups" Write-Host "其他管理组内的剩余VM数量: $vmInOtherMgmtGroups"
备选方案:Azure Resource Graph KQL查询
在Azure Resource Graph Explorer中执行以下查询,替换"YourSpecificString"为目标关键词,可直接获取统计结果:
Resources | where type =~ 'Microsoft.Compute/virtualMachines' | extend mgmtGroup = subscription().managementGroupNames | summarize TotalVMs = count(), VMInTargetMgmtGroups = countif(mgmtGroup has "YourSpecificString"), VMInOtherMgmtGroups = countif(not(mgmtGroup has "YourSpecificString")) | project TotalVMs, VMInTargetMgmtGroups, VMInOtherMgmtGroups
原KQL代码的中文说明
你提供的原始代码功能如下:
Resources | where type =~ 'Microsoft.Compute/virtualMachines' // 筛选所有虚拟机类型的资源 | Count // 统计资源总数 | project TotalVMs=Count // 将统计结果重命名为TotalVMs并输出
内容的提问来源于stack exchange,提问作者HereToLearn
相关产品推荐
相关产品推荐

