Skip to content

Instantly share code, notes, and snippets.

@SvenAelterman
Last active May 12, 2022 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SvenAelterman/0363bba42f968360405fe49f2ce3482c to your computer and use it in GitHub Desktop.
Save SvenAelterman/0363bba42f968360405fe49f2ce3482c to your computer and use it in GitHub Desktop.
Remove-Unattached-NICs
$deleteUnattachedNICs = $false
# List all unattached NICs
$unattachedNICs = Get-AzNetworkInterface | `
Where-Object { $_.VirtualMachine -eq $null -and ($_.PrivateEndpointText -eq $null -or $_.PrivateEndpointText -eq 'null') }
# Iterate over the unattached NICs
foreach ($nic in $unattachedNICs) {
# Find a lock for the NIC (or resource group/subscription/...)
$lock = Get-AzResourceLock -ResourceName $nic.Name -ResourceGroupName $nic.ResourceGroupName -ResourceType 'Microsoft.Network/networkInterfaces'
# If there is no lock
if (! $lock) {
# If this is a test run only
if (! $deleteUnattachedNICs) {
Write-Host "Would delete $($nic.Name)"
}
else {
Write-Host "Deleting $($nic.Name)"
try {
# Delete the NIC
Remove-AzNetworkInterface -Name $nic.Name -ResourceGroupName $nic.ResourceGroupName -Force
}
catch {
Write-Host "Failed to remove $($nic.Name): $_" -ForegroundColor Red
}
}
}
else {
Write-Host "Cannot delete $($nic.Name) due to resource lock"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment