Azure VM KQL脚本优化:如何获取CPU与内存信息
解决Azure KQL查询VM CPU和内存信息的问题
要获取VM的CPU和内存信息,有两种可行方案,以下分别说明:
方法一:关联Azure VM SKU资源(推荐)
Azure的microsoft.compute/virtualmachineskus资源存储了所有VM规格的官方参数,包括vCPU数量、内存大小等,通过关联该资源能精准获取数据,避免字符串解析带来的误差。
修改后的完整KQL脚本:
resources | where type == "microsoft.compute/virtualmachines" | join kind=leftouter ( resourcecontainers | where type == "microsoft.resources/subscriptions" | project subscription = name, subscriptionId ) on subscriptionId | extend nicId = tostring(properties.networkProfile.networkInterfaces[0].id) | join kind=leftouter ( resources | where type == 'microsoft.network/networkinterfaces' | project nicId = id, privateIPAllocation = properties.ipConfigurations[0].properties.privateIPAllocationMethod, privateIPAddress = properties.ipConfigurations[0].properties.privateIPAddress ) on nicId // 关联SKU资源提取CPU和内存参数 | join kind=leftouter ( resources | where type == "microsoft.compute/virtualmachineskus" | project vmSize = name, vCPUs = properties.capacity, memoryGB = properties.memoryInGB ) on vmSize = properties.hardwareProfile.vmSize | project name, subscription, resourceGroup, location, zones, properties.provisioningState, vmSize = properties.hardwareProfile.vmSize, vCPUs, memoryGB, properties.extended.instanceView.osName, properties.extended.instanceView.osVersion, properties.extended.instanceView.powerState.displayStatus, properties.licenseType, nicId, privateIPAllocation, privateIPAddress
说明:
- 新增的
join块从virtualmachineskus资源中提取对应VM规格的vCPU数(properties.capacity)和内存大小(properties.memoryInGB) - 该方案会自动适配Azure的SKU更新,不会因规格命名格式变化导致数据错误
方法二:从vmSize字段字符串提取(备选)
如果无法访问virtualmachineskus资源,可通过字符串解析从vmSize字段提取CPU信息,内存则需要根据不同VM系列的已知参数对应(不同系列CPU和内存比例固定)。
示例解析逻辑(可插入原脚本的extend或project阶段):
| extend // 提取vmSize中的CPU数字部分 vCPUs = toint(extract(@"_(\d+)s?_v?\d*$", 1, properties.hardwareProfile.vmSize)), // 根据VM系列匹配内存,需手动补充不同系列规则 memoryGB = case( properties.hardwareProfile.vmSize startswith "Standard_D", vCPUs * 4, properties.hardwareProfile.vmSize startswith "Standard_B", vCPUs * 1, properties.hardwareProfile.vmSize startswith "Standard_E", vCPUs * 8, toreal(null) )
局限性:
- 不同VM系列的内存比例不同,需要手动维护对应关系
- 若Azure更新SKU命名规则,解析逻辑会失效
内容的提问来源于stack exchange,提问作者Joris Willekens
相关产品推荐
相关产品推荐

