Resource not found when trying to delete a VM and associated resources

Billsborough, Scott/PDX 1 Reputation point
2021-07-16T17:01:08.603+00:00

I modified this code, https://social.technet.microsoft.com/wiki/contents/articles/53980.azure-delete-vm-and-all-associated-resources-using-powershell-script.aspx posted by ManU PhiliP to require a Resource Group name and Subscription ID. The reason I modified it is, a co-worker discovered we had VMs with the same name in different resource groups. I added the Subscription ID so I could run Set-AzContext because running the original script would often return the result "The VM name entered doesn't exist in your connected Azure Tenant! Kindly check the name entered and restart the script with correct VM name..." even if you copied the VM name from the portal. I am now getting this error when running the modified code:

The Resource 'Microsoft.Compute/disks/sbC1WUS0-APP999_disk1_08ba11abe7a54e00b8dcdbb46f5c6881' under resource group 'RG-DELETEVMTEST-DEV' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix

If you go to the suggested web page, Set-AzContext is suggested. The page also recommends confirming the missing resource in the portal which I have done.

Here is my modified code:

Write-Host -NoNewline -ForegroundColor Green "Please enter the VM name you would like to remove:"
$VMName = Read-Host
Write-Host -NoNewline -ForegroundColor Green "Please enter the Resource Group the VM is associated to:"
$RGName = Read-Host
Write-Host -NoNewline -ForegroundColor Green "Please enter the Subscription ID the VM is associated to:"
$SubID = Read-Host
Set-AzContext -Subscription $SubID
$vm = Get-AzVm -Name $VMName
if ($vm) {
Write-Host -ForegroundColor Cyan 'Resource Group Name is identified as-' $RGName
$diagSa = [regex]::match($vm.DiagnosticsProfile.bootDiagnostics.storageUri, '^http[s]?://(.+?)\.').groups[1].value
Write-Host -ForegroundColor Cyan 'Marking Disks for deletion...'
$tags = @{"VMName"=$VMName; "Delete Ready"="Yes"}
$osDiskName = $vm.StorageProfile.OSDisk.Name
$datadisks = $vm.StorageProfile.DataDisks
$ResourceID = (Get-Azdisk -Name $osDiskName).id
New-AzTag -ResourceId $ResourceID -Tag $tags | Out-Null
if ($vm.StorageProfile.DataDisks.Count -gt 0) {
    foreach ($datadisks in $vm.StorageProfile.DataDisks){
    $datadiskname=$datadisks.name
    $ResourceID = (Get-Azdisk -Name $datadiskname).id
    New-AzTag -ResourceId $ResourceID -Tag $tags | Out-Null
    }
}
if ($vm.Name.Length -gt 9){
    $i = 9
    }
    else
    {
    $i = $vm.Name.Length - 1
}
$azResourceParams = @{
 'ResourceName' = $VMName
 'ResourceType' = 'Microsoft.Compute/virtualMachines'
 'ResourceGroupName' = $RGName
}
$vmResource = Get-AzResource @azResourceParams
$vmId = $vmResource.Properties.VmId
$diagContainerName = ('bootdiagnostics-{0}-{1}' -f $vm.Name.ToLower().Substring(0, $i), $vmId)
$diagSaRg = (Get-AzStorageAccount | where { $_.StorageAccountName -eq $diagSa }).ResourceGroupName
$saParams = @{
  'ResourceGroupName' = $diagSaRg
  'Name' = $diagSa
}
Write-Host -ForegroundColor Cyan 'Removing Boot Diagnostic disk..'
if ($diagSa){
Get-AzStorageAccount @saParams | Get-AzStorageContainer | where {$_.Name-eq $diagContainerName} | Remove-AzStorageContainer -Force
}
else {
Write-Host -ForegroundColor Green "No Boot Diagnostics Disk found attached to the VM!"
}
Write-Host -ForegroundColor Cyan 'Removing Virtual Machine-' $VMName 'in Resource Group-'$RGName '...'
$null = $vm | Remove-AzVM -Force
Write-Host -ForegroundColor Cyan 'Removing Network Interface Cards, Public IP Address(s) used by the VM...'
foreach($nicUri in $vm.NetworkProfile.NetworkInterfaces.Id) {
   $nic = Get-AzNetworkInterface -ResourceGroupName $vm.ResourceGroupName -Name $nicUri.Split('/')[-1]
   Remove-AzNetworkInterface -Name $nic.Name -ResourceGroupName $vm.ResourceGroupName -Force
   foreach($ipConfig in $nic.IpConfigurations) {
     if($ipConfig.PublicIpAddress -ne $null){
     Remove-AzPublicIpAddress -ResourceGroupName $vm.ResourceGroupName -Name $ipConfig.PublicIpAddress.Id.Split('/')[-1] -Force
     }
    }
}
Write-Host -ForegroundColor Cyan 'Removing OS disk and Data Disk(s) used by the VM..'
Get-AzResource -tag $tags | where{$_.resourcegroupname -eq $RGName}| Remove-AzResource -force | Out-Null
Write-Host -ForegroundColor Green 'Azure Virtual Machine-' $VMName 'and all the resources associated with the VM were removed sucessfully...'
}
else{
Write-Host -ForegroundColor Red "The VM name entered doesn't exist in your connected Azure Tenant! Kindly check the name entered and restart the script with correct VM name..."
}

Any suggestion of what I can try to make the script see the disk?

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,014 questions
{count} votes

1 answer

Sort by: Most helpful
  1. prmanhas-MSFT 17,946 Reputation points Microsoft Employee Moderator
    2021-07-19T11:10:12.703+00:00

    @Billsborough, Scott/PDX Thank you for your patience over the matter!!!

    I am done with my repro and below are my findings:

    I tried to replicate the same environment in terms of the current condition as you mentioned in the query where you have 2 VM in separate Resource Groups with same name.

    First I tried the mentioned script which you were referring to and I can confirm I am getting the same error as per the Error handling outlined in the code:

    115858-image.png

    Then I tried running your script as it is and it was executed successfully without any error:

    115905-image.png

    As per the error mentioned by you in the query it seems that there is a possibility that the associated disk with Azure VM was not found under the Subscription. Now there can be a lot of reasons for same but one among them what I can think of is maybe the disk was deleted from portal itself beforehand maybe accidentally by someone. When you delete a resource, there may be a short amount of time when the resource still appears in the portal but isn't actually available and that is why you are hitting the error because script was not able to find that resource. Another general perception about this error is that the Subscription you selected is the Subscription in which you actually have the resource since one single tenant might have number of subscription and sometime there might be confusion on same. Now assuming from your verbatim it seems like you have already checked it but will request you to check once more.

    Now in case it is still not working let us do some testing. You can just try to create one test VM from scratch and then try to run same script as mentioned by you and see if it works for you or not because if it is working for me without any issue that rules out the possibility that script written by you is perfect for the work it is expected to do.

    For Disk part still if you want to check the current scenario you can add the below script snippet and check if it works for you or not:

    Get-AzDisk | where { $_.ManagedBy -eq $vm.Id } | Remove-AzDisk -Force

    if ('DataDiskNames' -in $vm.PSObject.Properties.Name -and @($vm.DataDiskNames).Count -gt 0) {
    Foreach ($uri in $vm.StorageProfile.DataDisks.Vhd.Uri) {
    $dataDiskStorageAcct = Get-AzStorageAccount -Name $uri.Split('/')2.Split('.')[0]
    $dataDiskStorageAcct | Remove-AzStorageBlob -Container $uri.Split('/')[-2] -Blob $uri.Split('/')[-1]
    }
    }

    Did some digging and found below as well which you might like to test out just in case:

    https://adamtheautomator.com/azure-vm-delete/
    https://vautomation.dev/2020/10/azure/azure-delete-vm-and-child-resources-using-powershell/

    Still I would recommend you to go ahead and test your script on a freshly created VM in your Subscription to see if it works for you.

    Also there has been feedback as well here to actually bring this as an option on Portal. Currently When you delete a virtual machine (VM) in Azure, by default, any disks that are attached to the VM aren't deleted. This feature helps to prevent data loss due to the unintentional deletion of VMs.

    Still if you want to investigate further into this I would recommend you to open a Support Case so they can check your environment and help you to figure out root cause. If you don't have any Support Plan do let me know I can help with one time free Support as well :)

    Hope it helps!!!

    Please "Accept as Answer" if it helped so it can help others in community looking for help on similar topics.


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.