Get Azure VMs status using PowerShell script

VMs status

In one of the previous articles, I shared a script for gathering logs from Azure. This time I wanted to show you how get VMs status.

Azure VMs status

To check status of your servers you need few things:

  • Azure Credentials
  • Environment
  • TenantID
  • Subscription
  • Resource Group Name

Below you can find example for converting your password to secure string and adding it with account ID to azure credentials variable:

$SecPasswd = ConvertTo-SecureString "67t1uS5HfXCc9L4d3P02" -AsPlainText -Force
$AzureCred = New-Object System.Management.Automation.PSCredential ("", $SecPasswd)

Now, when credentials are set you can use Add-AzureRmAccount which adds an authenticated account to use for Azure Resource Manager cmdlet requests.

Add-AzureRmAccount -Environment AzureBros -TenantId e0527c39-0369-376d-b139-342dcd316geb -Subscription 'PowerShellBros 1' -Credential $AzureCred

Below you can find a simple script on how to get status of your VMs using Get-AzureRmVM command. I wanted to display the following properties ResourceGroupName, Name, Location, PowerState:

$SecPasswd = ConvertTo-SecureString "67t1uS5HfXCc9L4d3P02" -AsPlainText -Force
$AzureCred = New-Object System.Management.Automation.PSCredential ("", $SecPasswd)
Add-AzureRmAccount -Environment AzureBros -TenantId e0527c39-0369-376d-b139-342dcd316geb -Subscription 'PowerShellBros 1' -Credential $azurecred

#Get VM status and add results to variable
$AllVMs = Get-AzureRmVM -ResourceGroupName ps_bros -Status | Select-Object ResourceGroupName,Name,Location, @{ label = “VMStatus”; Expression = { $_.PowerState } } 

#Or get VM status where server names match VM and add results to variable
$AllVMs = Get-AzureRmVM -ResourceGroupName ps_bros -Status | Where-Object {$ -match "VM"} | Select-Object ResourceGroupName,Name,Location, @{ label = “VMStatus”; Expression = { $_.PowerState } } 

#Display results in console
$AllVMs | Format-Table -Auto -Wrap

#Display results in new window
$AllVMs | Out-GridView -Title "Azure VMs"

#Display running VMs in console
$AllVMs | Where-Object {$_.Status -eq "VM running"}

#Export results to CSV file on your desktop
$AllVMs | Export-Csv "c:\users\$env:username\desktop\Azure_VMs.csv" -Force -NoTypeInformation

I hope this was informative for you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.