Find and Delete all Orphaned Azure NICs and

Here’s a script that will find all the Azure Network interfaces that are orphaned/Unattached and remove them.

# Check and Delete Azure Orphaned Unattached NICs
              # Gather all the NICs in your subscription
              Connect-Azaccount
              $allNICs = Get-AzNetworkInterface

              # Gather all the VMs in your subscription
              $allVMs = Get-AzVM

              # Create an array to store orphaned NICs
              $orphanedNICs = @()

              # Loop through each NIC to find orphaned ones
              foreach ($nic in $allNICs) {
                  $isOrphaned = $true
                  
                  # Check if the NIC is attached to any VM
                  foreach ($vm in $allVMs) {
                      if ($nic.VirtualMachine -ne $null -and $nic.VirtualMachine.Id -eq $vm.Id) {
                          $isOrphaned = $false
                          break
                      }
                  }
                  
                  # If NIC is orphaned, add it to the list
                  if ($isOrphaned) {
                      $orphanedNICs += $nic
                  }
              }

              # Delete the orphaned NICs, if any
              if ($orphanedNICs.Count -gt 0) {
                  Write-Host "Orphaned Unattached NICs found. Deleting them..."

                  foreach ($nic in $orphanedNICs) {
                      Write-Host "Deleting NIC with ID:" $nic.Id
                      #Remove-AzNetworkInterface -ResourceId $nic.Id -Force -Whatif
                      Write-Host "Deleted NIC with ID:" $nic.Id
                  }

                  Write-Host "Orphaned Unattached NICs have been gracefully removed from your Azure Environment."
              } else {
                  Write-Host "Congratulations! No orphaned unattached NICs were found."
              }
Share or Save this:
Share

Leave a Reply

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