Here’s a script that will find all the Azure Network interfaces that are orphaned/Unattached and remove them. Excludes any Private Endpoints and uses Resource Graph to quickly find the NICs.
# Define the subscription ID
$subscriptionId = '1234'
# Define the Resource Graph query
$query = @"
resources
| where type == 'microsoft.network/networkinterfaces'
| where subscriptionId == '$subscriptionId'
| extend vmId = properties.virtualMachine.id
| where isnull(vmId)
| where isnull(properties.privateEndpoint)
"@
# Run the Resource Graph query
$orphanedNICs = Search-AzGraph -Query $query
Write-Output $orphanedNICs
# Check if there are any orphaned NICs
if ($orphanedNICs.Count -gt 0) {
Write-Host "Orphaned Unattached NICs found. Deleting them..."
foreach ($nic in $orphanedNICs) {
$nicDetails = Get-AzNetworkInterface -ResourceId $nic.id
Remove-AzNetworkInterface -Name $nicDetails.Name -ResourceGroupName $nicDetails.ResourceGroupName -Force -WhatIf
Write-Host "Deleted NIC with ID:" $nic.id
}
Write-Host "Orphaned Unattached NICs have been removed from your Azure Environment."
} else {
Write-Host "Congratulations! No orphaned unattached NICs were found."
}