Update : updated script to support Azure Az powershell module.
Azure Unmanaged disk is a Microsoft provided Virtual machine disk solution. However, this is not in use so much now-a-days since the introduction of Managed disk. With unmanaged disk, you have to create a Storage Account to store the disk files (VHDs) as Blobs and you are responsible for managing it through out the life cycle. Where as, with managed disk, everything is managed by Microsoft and not having the visibility of the Virtual machine disks anymore.
In this post, I am going to provide a script which will list out all unmanaged disks created in Azure subscriptions you manage and their status if they are actually attached to a Virtual machine. Why I wanted to do it? I was working in a project to reduce Azure expenses and identify all Azure wastes we have in our subscriptions. Ideally, every unattached disk is my target and find out how many of those can be deleted to save some money here.
Make sure you have Azure Az Module installed and imported on the system before running this script. For more information on how to install and configure Az module refer following article : https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-5.5.0
Before running the script, login to Azure using Login-AzAccount command.
Once logged in, run the script as provided below.
$date = Get-Date -UFormat "%m-%d-%Y"
$currentDir = $(Get-Location).Path
$oFile = "$($currentDir)\AzureUnManagedDisk_Details_$($date).csv"
if(Test-Path $oFile){Remove-Item $oFile -Force}
"StorageAccountName,ResourceGroupName,ContainerName,BlobName,BlobStatus,SizeInGB" | Out-File $oFile -Append -Encoding ASCII
$allStorageAccounts = Get-AzStorageAccount
ForEach($storageAccount in $allStorageAccounts){
$storageAccountName = $storageAccount.StorageAccountName
$resourceGroupName = $storageAccount.ResourceGroupName
$storageAccountContext = $storageAccount.Context
$storageAccountContainer = Get-AzureStorageContainer -Context $storageAccountContext
foreach($container in $storageAccountContainer){
$blobs = Get-AzureStorageBlob -Container $container.Name -Context $storageAccountContext
foreach($blob in $blobs){
$sizeInGB = $containerName = $blobName = $blobStatus = ""
if($blob.Name -match ".vhd"){
$containerName = $container.Name
$blobName = $blob.Name
$sizeInGB = $blob.Length / 1024 / 1024 / 1024
$blobStatus = $blob.ICloudBlob.Properties.LeaseStatus
"$storageAccountName,$resourceGroupName,$containerName,$blobName,$blobStatus,$sizeInGB" | Out-File $oFile -Append -Encoding ASCII
}
}
}
}
If you are interested in saving, take a look at the Status of those Blobs which are in unlocked/unassigned state. That’s it, now you have the CSV file report which you can use and start working on the next step.
Let me know if you have any issue on running the script or if you have any suggestion to improve it.