如何高效查看Azure中200+台虚拟机(VM)的状态?
批量获取Azure虚拟机状态的简便方法
1. 利用Azure CLI一次性查询所有资源的VM状态
无需逐个指定资源组,直接查询当前订阅下所有虚拟机的状态,还可自定义输出字段:
az vm list --all -d -o table --query "[].{VM名称:name, 资源组:resourceGroup, 电源状态:powerState}"
--all:查询订阅下所有资源组的VM(默认仅查当前资源组)-d:包含实例视图数据(即电源状态等运行时信息)--query:自定义输出字段,可按需调整字段名和内容
若需跨多个订阅查询,可通过--subscription参数批量指定:
az vm list --all -d -o table --subscription <订阅ID1>,<订阅ID2> --query "[].{VM名称:name, 订阅:subscriptionId, 资源组:resourceGroup, 电源状态:powerState}"
2. 用Azure Resource Graph高效批量查询
针对200台以上的大规模虚拟机,Resource Graph查询速度远快于常规CLI命令,适合批量分析:
az graph query -q "Resources | where type == 'Microsoft.Compute/virtualMachines' | project VM名称=name, 资源组=resourceGroup, 电源状态=properties.extended.instanceView.powerState.code"
可添加过滤条件缩小范围,比如仅查询特定资源组的VM:
az graph query -q "Resources | where type == 'Microsoft.Compute/virtualMachines' and resourceGroup == '<目标资源组>' | project VM名称=name, 电源状态=properties.extended.instanceView.powerState.code"
3. 关于Graph API的说明
Graph API主要用于Azure AD相关资源(如用户、组、应用),虚拟机属于Azure资源管理范畴,更适合使用Azure Resource Manager (ARM) API:
调用ARM的虚拟机列表接口,可批量获取带电源状态的VM信息:
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines?api-version=2023-07-01&$expand=instanceView
返回结果中,properties.extended.instanceView.powerState.code字段即为虚拟机电源状态(如PowerState/running、PowerState/deallocated)。
内容的提问来源于stack exchange,提问作者souser
相关产品推荐
相关产品推荐

