PowerShell to list ASM VMs, Size and CloudService | Azure

I’ve been asked several times now to help customers running IaaS VMs in the Classic mode (ASM Mode) analyse their resources.

The following will list your classic VMs out by CloudService, VMName and VMSize to a CSV file.

You’ll need to edit the location of the file.

Please note this is not meant to be a very sophisticated script just to get you to the answer.

Happy hunting!

<# .DESCRIPTION An example runbook which gets all the Classic VMs in a subscription using the Classic Run As Account (certificate) and then shuts down running VMs .NOTES AUTHOR: Azure Automation Team + Jonathan Wade LASTEDIT: 28-08-2016 #>

$ConnectionAssetName = "AzureClassicRunAsConnection"
$ServiceName = "wadeclassiv01"

# Get the connection
$connection = Get-AutomationConnection -Name $connectionAssetName

# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
if ($Conn -eq $null)
{
throw "Could not retrieve connection asset: $ConnectionAssetName. Assure that this asset exists in the Automation account."
}

$CertificateAssetName = $Conn.CertificateAssetName
Write-Verbose "Getting the certificate: $CertificateAssetName" -Verbose
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
if ($AzureCert -eq $null)
{
throw "Could not retrieve certificate asset: $CertificateAssetName. Assure that this asset exists in the Automation account."
}

Write-Verbose "Authenticating to Azure with certificate." -Verbose
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID

# Get cloud service

$VMs = Get-AzureVM -ServiceName $ServiceName

# Stop each of the started VMs
foreach ($VM in $VMs)
{
if ($VM.PowerState -eq "Stopped")
{
# The VM is already stopped, so send notice
Write-Output ($VM.InstanceName + " is already stopped")
}
else
{
# The VM needs to be stopped
$StopRtn = Stop-AzureVM -Name $VM.Name -ServiceName $VM.ServiceName -Force -ErrorAction Continue

if ($StopRtn.OperationStatus -ne 'Succeeded')
{
# The VM failed to stop, so send notice
Write-Output ($VM.InstanceName + " failed to stop")
}
else
{
# The VM stopped, so send notice
Write-Output ($VM.InstanceName + " has been stopped")
}
}
}

Disclaimer:  Please note although I work for Microsoft the information provided here does not represent an official Microsoft position and is provided as is.

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.