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

使用Azure Graph查询虚拟机核心数的脚本问题求助

解决Azure Resource Graph查询虚拟机核心数为空的问题

问题原因

你用到的properties.hardwareProfile.vmSizeProperties字段**仅存在于弹性规格的虚拟机(Flexible VM)**资源属性中,普通固定规格的虚拟机没有这个字段,直接取值会返回空值。

解决方案

区分弹性VM和普通VM,分别获取核心数:

修改后的Kusto查询

Resources 
| join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project subscriptionName=name, subscriptionId) on subscriptionId
| where type =~ 'Microsoft.Compute/virtualMachines'
| extend HUBEnabled = iff(isempty(tostring(properties.['licenseType'])), "No", "Yes")
| extend osType = tostring(properties.storageProfile.osDisk.osType)
| extend VMSize = tostring(properties.hardwareProfile.vmSize)
| extend VMStatus = tostring(properties.extended.instanceView.powerState.displayStatus)
| extend nics=array_length(properties.networkProfile.networkInterfaces)
// 核心逻辑:弹性VM取当前配置的vCPU,普通VM通过SKU映射核心数
| extend vCPU = case(
    isnotempty(properties.hardwareProfile.vmSizeProperties), tostring(properties.hardwareProfile.vmSizeProperties.currentVCPUCount),
    // 以下为常用VM SKU的vCPU映射示例,可根据实际环境补充
    VMSize startswith "Standard_D2s_v3", "2",
    VMSize startswith "Standard_D4s_v3", "4",
    VMSize startswith "Standard_D8s_v3", "8",
    VMSize startswith "Standard_A2_v2", "2",
    VMSize startswith "Standard_F2s_v2", "2",
    // 未匹配的SKU直接显示规格名称,便于后续补充映射
    VMSize
)
| extend OSName = tostring(properties.osProfile.computerName)
| extend Location = tostring(location)
| mv-expand nic=properties.networkProfile.networkInterfaces
| where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic)
| extend nicId = tostring(nic.id)
| join kind=leftouter (
    Resources
    | where type =~ 'microsoft.network/networkinterfaces'
    | extend ipConfigsCount=array_length(properties.ipConfigurations)
    | mv-expand ipconfig=properties.ipConfigurations
    | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true'
    | project nicId = id, privateIpAddress = tostring(ipconfig.properties.privateIPAddress))
| project VMName = name, computer_name=OSName, VMSize, vCPU, Location, osType, VMStatus, Private_IP=privateIpAddress, HUBEnabled, subscriptionName, subscriptionId, resourceGroup

关键说明

  1. 弹性VM处理:弹性VM的vmSizeProperties包含currentVCPUCount(当前实际配置的核心数)、minVCPUCount和maxVCPUCount(弹性调整范围),可根据需求替换取值字段。
  2. 普通VM处理:固定规格VM的核心数由SKU决定,通过case语句映射常用SKU的核心数;如果需要覆盖所有SKU,可以预先将Azure VM规格的元数据导入临时表,再通过SKU名称关联查询。
  3. 无效关联移除:原查询中最后一步与虚拟机规模集(VMSS)的关联逻辑错误(网卡ID与VMSS ID不匹配),已移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:40:24