Last active
May 12, 2022 02:28
-
-
Save SvenAelterman/0363bba42f968360405fe49f2ce3482c to your computer and use it in GitHub Desktop.
Remove-Unattached-NICs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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