Clean up unused Azure VHD Disks


Azure Virtual Machine Disks

The Microsoft Azure platform maintains a list of VHD blobs that have been registered as “disks” in your Azure subscription. You can view a list of registered “disks” by opening the Azure Portal, going to the Virtual Machines node, and selecting the Disks link. Each Azure disk has a property called AttachedTo that indicates which Azure VM the disk is attached to. Disks that aren’t attached to any virtual machine are not in use, and might be good candidates for cleanup. Cleaning up unused Azure disks will save you the cost for Azure storage, to maintain the disk in blob storage.

Disk Cleanup

Using Azure PowerShell, we can easily clean up disks that are unused. You could implement this PowerShell script as an automated task through the Microsoft Azure Automation feature, which is still in preview as of this writing. Azure Automation is a script-as-a-service feature of the Azure platform that allows you to execute PowerShell Workflows (also known as Runbooks) directly from Azure. Using this service, you can ensure that your Azure subscriptions are well-managed automatically.

Of course, if you implement any automated clean-up processes like this, you’ll want to make sure that you have a backup plan, and communicate to the rest of your team that this process will be executed on a scheduled basis. If other team members are not aware of this process, they might leave orphaned disks out there unintentionally, thinking that they won’t be cleaned up automatically.

Here is a script that we can use to perform the automated cleanup. If you want to wrap this script inside a PowerShell Workflow, you could easily do that as well. However, the Where() and ForEach() methods may not be suitable for Workflows.

# Authenticate to the Microsoft Azure platform
$Username = ''; # Change this to your Azure Active Directory organizational account username.
$AzureCredential = Get-Credential -UserName $Username -Message 'Please enter your Azure password.';
Add-AzureAccount -Credential $AzureCredential;

# Find and remove unused Azure disks
(Get-AzureDisk).Where({ !$PSItem.AttachedTo; }).ForEach({ Remove-AzureDisk -DiskName $PSItem.DiskName -DeleteVHD; });

After running the script above, you will have cleaned up your unused Azure VHD. The output from the Remove-AzureDisk command looks similar to the following screenshot.