Open In App

Microsoft Azure – Delete Orphaned Disks using PowerShell Script

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will use an Azure PowerShell Module Script that finds all the unattached or orphaned azure managed disks in azure and delete them.

PowerShell Script to Delete Orphaned Disks in Azure:

The below Power Shell Script will find all the orphaned azure managed disks and will delete all the orphaned managed disks one after the other in loop un till it finishes.

Note: Script execution time depends on the numbers of orphaned managed disks in azure.

Check Unattached Disk Resources:

Firstly, run the below script to verify the unattached disk resources before deleting the orphaned managed disks –

$SubscriptionName = "_add_subscription_name_here"
Set-AzureRmContext -SubscriptionName "$SubscriptionName" | Out-Null

$Disk = Get-AzDisk
$Orphan = $Disk | Select-Object -Property Name,ResourceGroupName,Type,DiskSizeGB,DiskState

$state_unattached = $Orphan | Where-Object -Property DiskState -eq “Unattached”

#Find and Delete - Unattached State Disk
Foreach ($disks in $state_unattached){

    $ResourceGroup=$disks.ResourceGroupName
    $DiskName=$disks.Name
    $DiskState=$disk.DiskState
    
    Write-Host "Disk Name        : $DiskName"
    Write-Host "ResourceGoupName : $ResourceGroup"
    Write-Host ""
}

The above script returns the list of all orphaned disks with Disk Name and Resource Group Name within the select subscription.

Output:

PowerShell Script to Delete Orphaned Disks:

Run the below script to delete orphaned managed disks in azure for the select scope or subscription.

$SubscriptionName = "_add_subscription_name_here"
Set-AzureRmContext -SubscriptionName "$SubscriptionName" | Out-Null

$Disk = Get-AzDisk
$Orphan = $Disk | Select-Object -Property Name,ResourceGroupName,Type,DiskSizeGB,DiskState

$state_unattached = $Orphan | Where-Object -Property DiskState -eq “Unattached”

#Find and Delete - Unattached State Disk
Foreach ($disks in $state_unattached){
    $ResourceGroup=$disks.ResourceGroupName
    $DiskName=$disks.Name
    $DiskState=$disk.DiskState
    Write-Host "Disk Name        : $DiskName"
    Write-Host "ResourceGoupName : $ResourceGroup"
    Write-Host "Disk State       : $DiskState"
    Write-Host "Deleting unattached Managed Disk"
    $disks | Remove-AzDisk -Force
    Write-Host "Successfully Deleted"
    Write-Host ""
}

the above script returns the list of all orphaned disks that are successfully deleted. The console prints the Disk Name and Resource Group Name.

Note: Install Azure PowerShell Modules if not installed. In case you are using a Windows PowerShell.

Output:


Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads