PowerShell Genie

Inventory Azure VMs

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Get-AzVM with -Status queries each machine's instance view in addition to its model, and that is what populates the PowerState property.

The script

1PS> Get-AzVM -Status | Select-Object Name,ResourceGroupName,Location,PowerState

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 ResourceGroupName Name Location PowerState
    2 ----------------- ----- ------------ --------------
    3 RG-PROD WEB01 eastus VM running
    4 RG-PROD APP01 eastus VM running
    5 RG-DEV DEV01 centralindia VM deallocated
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    Get-AzVM -Status | Select-Object Name,ResourceGroupName,Location,PowerState
    1. Stage 1Get-AzVM-Status
    2. Stage 2Select-ObjectPositional values or no named parameters

      How it works

      Get-AzVM with -Status queries each machine's instance view in addition to its model, and that is what populates the PowerState property. The projection keeps the name with its resource group, region, and that power state.

      Adapting it

      Restrict the sweep with -ResourceGroupName when only one workload is in question, which also avoids making the extra status calls against everything else in the subscription.

      Requirements

      Az.Compute with a Connect-AzAccount session and Reader on the subscription.

      If the result is unexpected

      The VM inventory misses machines in other subscriptions.

      Resource queries commonly use the current subscription context rather than every accessible subscription.

      1. Confirm the current subscription and explicitly iterate the approved subscription scope where required.

      Validate the result

      Each VM row identifies its subscription and resource group.

      Keep the check reliable

      Do not merge multi-subscription output without retaining those identifiers.

      Primary documentation

      PowerShell objects and pipelines documentation

      Practise the script’s building blocks

      Read Azure VM status

      An Azure read context is preloaded in this fictional lab. Return the fictional Azure VM status inventory.

      Review the lesson

      Continue
      Genie guideInventory Azure VMs

      Get-AzVM with -Status queries each machine's instance view in addition to its model, and that is what populates the PowerState property.