Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SQLtattoo/b13336a30211543e656bc13b51b764b3 to your computer and use it in GitHub Desktop.
Save SQLtattoo/b13336a30211543e656bc13b51b764b3 to your computer and use it in GitHub Desktop.
# !!! Make sure you don't delete unintentionally disks you might need
# Set deleteUnattachedDisks=1 if you want to delete unattached Managed Disks
# Set deleteUnattachedDisks=0 if you want to see the Id of the unattached Managed Disks
$deleteUnattachedDisks=0
$managedDisks = Get-AzDisk
$k=0
$l=0
foreach ($md in $managedDisks) {
# ManagedBy property stores the Id of the VM to which Managed Disk is attached to
# If ManagedBy property is $null then it means that the Managed Disk is not attached to a VM
if($md.ManagedBy -eq $null){
$k+=1
if($deleteUnattachedDisks -eq 1){
Write-Host "Deleting unattached Managed Disk with Id: $($md.Id)"
$md | Remove-AzDisk -Force
Write-Host "Deleted unattached Managed Disk with Id: $($md.Id) "
$l+=1
}else{
$md.Id
}
}
}
Write-Host "Unmanaged disks found: " $k "/ deleted: " $l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment