PowerShell script to get all Azure VM status in multiple subscriptions

In this article, I will show you a simple powershell script to get all azure VM status in multiple subscriptions quickly.

Sometime we need the status of the virtual machines which are running in multiple subscriptions like Dev, Prod.

Even you can check status on Azure portal itself but it is bit difficult to pull all VM status in one go.

So let’s draft the easy and simple code to get the script ready for you.

Before you deep in, make sure you have right privillage to login via Azure portal, Azure CLI or AzureRM module install on your local machine to run this script in powershell terminal.

Note-This script will collect all VMs including the status, OS Type, Version, VM, Location, Resorce Group and Subscription Name.

## Define Variables($Subscription) to collect subscription details and $Report to store all VM status along with OS Type, OS Version, VM Name, RG Name.

$Subscriptions = Get-AzureRmSubscription | Where-Object { $_.Name -in ("Prod", "Dev") }
$Report = ForEach ($Subscription in $Subscriptions) {
     $SubscriptionName = $Subscription.Name
     Set-AzureRmContext -SubscriptionName "$SubscriptionName" | Out-Null
     $RGs = Get-AzureRMResourceGroup
     foreach ($RG in $RGs) {
         $VMs = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName
         foreach ($VM in $VMs) {
             # VM Status (running/deallocated/stopped)
             $VMDetail = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName -Name $VM.Name -Status
             $VMStatusDetail = $VMDetail.Statuses.DisplayStatus -match "^VM .*$"
             New-Object psobject -Property @{
                 "SubscriptionName" = $SubscriptionName
                 "VMName"           = $VM.Name
                 "VMStatus"         = "$VMStatusDetail"
                 "OSType"           = $VM.StorageProfile.OSDisk.OSType
                 "OSVersion"        = $Vm.StorageProfile.ImageReference.Sku
                 "ResourceGroup"    = $RG.ResourceGroupName
                 "Location"         = $VM.Location
               }
          }
     }
 }
## End Subscription
## Pull the $Report variable to get all details and save in csv format.
$Report | Export-Csv "c:\users\$env:username\documents\Azure_VMs_Status.csv" -Force -NoTypeInformation

I hope this will help to save your lots of effort to get such details. You may also check another article to get Azure VM status here.

About Shachindra Yadav

I, Shachindra Yadav, a Cloud Certified, DevOps and technology enthusiastic person, more passionate to learn and write blogs in my free time.

View all posts by Shachindra Yadav →