Azure – Clearing out all the data, VMs, VHDs and Clouds from an Azure tenant

There are times when you need to reset a Azure tenant and remove all the data from it.  If you only have a small installation this can be done simply via the Portal web interface.  The last one I had to do have over 30 VMs and over 80 VHDs….I didn’t want to do that lot by hand.  So I put together some simple PowerShell scripts to wiz through the various parts of the tenant and get rid of everything.

Shutdown all VMs in a subscription

Select-AzureSubscription -SubscriptionName “SubScriptionName”
foreach ($vm in Get-AzureVM)
{
$name = $vm.Name
$servicename = $vm.ServiceName

If($vm.Status -ne ‘StoppedDeallocated’)
{
# Add the VM’s which should not be shutdown
Write-Host ‘Stopping ‘ + $name
Stop-AzureVM -Service $servicename -name $name
}
}

Delete all VMs in a subscription

Select-AzureSubscription -SubscriptionName “SubScriptionName”
foreach ($vm in Get-AzureVM)
{
$name = $vm.Name
$servicename = $vm.ServiceName
Write-Host ‘Stopping ‘ + $name
Remove-AzureVM -Service $servicename -name $name -DeleteVHD
}

Delete all remaining disks from a subscription

Select-AzureSubscription -SubscriptionName “SubScriptionName”
foreach ($disk in Get-AzureDisk)
{
$name = $disk.DiskName
Write-Host ‘Deleting ‘ + $name
Remove-AzureDisk $name
}

Remove all storage accounts

Select-AzureSubscription -SubscriptionName “SubScriptionName”
foreach ($storageac in Get-AzureStorageAccount)
{
$name = $storageac.StorageAccountName
Write-Host ‘Deleting ‘ + $name
Remove-AzureStorageAccount $name
}

Delete all cloud services

Select-AzureSubscription -SubscriptionName “SubScriptionName”
foreach ($cloud in Get-AzureService)
{
$name = $cloud.ServiceName
Write-Host ‘Deleting ‘ + $name
Remove-AzureService $name -force
}

Leave a Reply

Your email address will not be published. Required fields are marked *