Bulk deletion of virtual machines and their disks

Shripad Limaye 1 Reputation point
2022-03-24T22:21:37.243+00:00

Hi,

I am having a task to delete 150+ virtual machines. I understand that deleting virtual machine will not automatically delete the disks attached to it. In this case, identifying the those disks and deleting correct disks will be time consuming tasks. We have a script that blindly deletes all the disks not attached to anywhere, but I am looking for finding disks attached specifically to machines in my deletion list.

How can I make sure that the disks get deleted along with virtual machine deletion?

Secondly, is there any script that can be used to input virtual machine names from a csv file and delete them including the disks? Or is there any way I can list all the disks attached to those 150+ machines and use the list to delete those disks after the machines are deleted?

Thanks,
Shri

Azure Disk Storage
Azure Disk Storage
A high-performance, durable block storage designed to be used with Azure Virtual Machines and Azure VMware Solution.
668 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. shiva patpi 13,366 Reputation points Microsoft Employee Moderator
    2022-03-25T01:03:26.87+00:00

    Hello @Shripad Limaye ,
    Based upon your multiple requirements I am providing you couple of bits and pieces of the azure powershell commands which you can combine and leverage to-gether:

    1) To Get list of all the Disks and their Corresponding Virtual Machine names you can use the below command:

    Get-AzureRmDisk | Select Name , ManagedBy
    (ManagedBy column denotes which Disk is being used by which Virtual Machine)
    (You can apply the filters for the above command like: Get-AzureRmDisk | where -FilterScript {$_.ManagedBy -contains "something"} | select Name , ManagedBy )

    Sample Output:

    186732-image.png

    2 . To Identity the VMs and their Corresponding disks

    $vms = Get-AzureRmVM // To get all the VMs
    $vm = Get-AzureRMVM -Name $vms[0].Name -ResourceGroupName $vms[0].ResourceGroupName //Get one of the VM details
    $vm.StorageProfile //It will show OsDisk & DataDisk

    186693-image.png

    You can loop through all the VMs & Corresponding Disks:

    ** Finally use Remove-AzureRmDisk by providing the ResourceGroup and Disk Name.**

    You can combine all those 3 commands. I think you will have a good script as per your requirements.

    Kindly let us know if you have additional questions !

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.