06 March 2019

Azure: find virtual machines without or with disabled Auto-shutdown using PowerShell

Auto-shutdown is a great feature to reduce Azure costs. However, I was not able to find a good way to get an overview which machine does not have Auto-shutdown enabled/configured while having a large number of virtual machines (VM) in multiple Azure subscriptions.

Found a nice PowerShell script at Stackoverflow.com and tweaked it a little bit to match my requirements. It works only for ARM machines, will not detect Classic ones.

Remember to run Connect-AzureRmAccount to establish Azure connection before running the script below:

###################
##:List all subs which are enabled
#$AllSubID = (Get-AzureRmSubscription | Where {$_.State -eq "enabled"}).SubscriptionId
### above might not work depends on account, just get all below.
$AllSubID = (Get-AzureRmSubscription).SubscriptionId
Write-Output "$(Get-Date -format s) :: List of Subscription below"
$AllSubID


$AllVMList = @()
Foreach ($SubID in $AllSubID) {
Select-AzureRmSubscription -Subscriptionid "$SubID"

##list all VMs
$VMs = Get-AzureRmVM
Foreach ($VM in $VMs) {
    $VM = New-Object psobject -Property @{`
        "Subscriptionid" = $SubID;
        "ResourceGroupName" = $VM.ResourceGroupName;
        "VMName" = $VM.Name}
        $AllVMList += $VM | select Subscriptionid,ResourceGroupName,VMName
        }
}

$AllVMList

## Get AutoShutdown info
Foreach ($VM in $AllVMList) {
    $ScheduledShutdownResourceId = "/subscriptions/$($VM.Subscriptionid)/resourceGroups/$($VM.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($VM.VMName)"
    #Write-Output "$ScheduledShutdownResourceId"

    try {
        $VMShutdownInfo = get-AzureRmResource -ResourceId $ScheduledShutdownResourceId
    }
    catch
    {
        $VMShutdownInfo = $null
    }

    #Write-Output "$VMShutdownInfo"

    if ($VMShutdownInfo)
    {
        if ($VMShutdownInfo.properties.status -eq "Disabled")
        {
        Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: $($VM.ResourceGroupName) :: $($VM.Subscriptionid)"
        Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: status: $($VMShutdownInfo.properties.status); taskType: $($VMShutdownInfo.properties.taskType) ; timeZoneId: $($VMShutdownInfo.properties.timeZoneId) ; dailyRecurrence: $($VMShutdownInfo.properties.dailyRecurrence) ;  "
        }
    }
    else
    {
        Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: $($VM.ResourceGroupName) :: $($VM.Subscriptionid)"
        Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: status: Shutdown not set"
    }   
}
###Done

No comments:

Post a Comment