Get Azure VM status using PowerShell Script

We can use the Get-AzureRmVM cmdlet to get the provisioning and power state (running status) of an Azure VM (Virtual Machine). Before start, install the Azure Powershell module to use this command.

Run the following command to connect Azure PowerShell, sign in with your Azure credentials.

# Connect to Azure
Connect-AzureRmAccount

To check the running status of a VM, we need the name of the VM and the name of the resource group in which the VM is located.

# Provide a resource group name 
$RGName = "RG-01"     
# Provide virtual machine name 
$VMName = "VM-01" 
$VMStatuses = (Get-AzureRmVM -ResourceGroupName $RGName -Name $VMName -Status). Statuses
$ProvisioningState = $VMStatuses[0].DisplayStatus
$PowerState = $VMStatuses[1].DisplayStatus
$VMStatuses.DisplayStatus

Check Status of All the Azure VMs

Run the following commands to get virtual machines from all the available resource groups and find the running status and provisioning state of all the machines.

$Result = @()
#Get all Resource groups
$AllRGs = Get-AzureRMResourceGroup
$TotalGroups = $AllRGs.Count
$i = 1 
ForEach ($RG in $AllRGs) {
Write-Progress -Activity "Processing $($RG.ResourceGroupName)" -Status "$i out of $TotalGroups Resource groups completed"
#Fetch virtual machines in the group
$VMList = Get-AzureRmVM -ResourceGroupName $RG.ResourceGroupName -Status
 
ForEach ($VM in $VMList) {
$Result += New-Object PSObject -property $([ordered]@{ 
VMName = $VM.Name
VMStatus  = $VM.PowerState
ProvisioningState = $VM.ProvisioningState
ResourceGroup = $VM.ResourceGroupName
Location = $VM.Location
})
}
$i++
}
$Result | FT

Export power and provisioning state of All Azure VMs

The above commands retrieve VM details from all the resource groups and keep the output in the variable $Result. Once you have successfully run the above commands, then run the below command to export the status of all VMs to a CSV file.

$Result | Export-CSV "C:\AllAzureVMStatus.CSV" -NoTypeInformation -Encoding UTF8

Find Stopped Azure VMs

You can filter results by VMStatus to list all the VMs that are in the stopped state.

$Result | Where-Object { $_.VMStatus -Like 'VM deallocated' }

Find and List Running Azure VMs

The below command just returns the list of VMs which are in running state.

$Result | Where-Object { $_.VMStatus  -Like 'VM running' }
Advertisement