How to list and remove unused (orphanip) public ip address "such as search if the ip is not associated to any Vm or Networkinterface card find and then delete" in azure using powershell azure automation runbook.
Getting this error "Method ‘get_SerializationSettings’ in type ‘Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient’ from assembly ‘Microsoft.Azure.Commands.ResourceManager.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ does not have an implementation."
Run Login-AzureRmAccount to login.
[CmdletBinding(SupportsShouldProcess=$true,
ConfirmImpact="High")]
Param
(
# Specifies the name of the resource group from which Public IP Addresses are to be retrieved.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]$ResourceGroup,
# Only lists Azure Network Interfaces that are not linked to an existing Azure Virtual Machine
[switch]$ListOnly
)
Begin
{
If (AzureRmResourceGroup -Name $ResourceGroup -ErrorAction SilentlyContinue )
{
$az_publicipaddress = Get-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroup
$RemAzPublicIP = $az_publicipaddress | Where-Object {$_.IpConfiguration -eq $null}
}
Else
{
Write-Error "Provided resource group does not exist: $ResourceGroup"
Throw
}
}
Process
{
$removed = @()
If ($PSBoundParameters.ContainsKey("ListOnly"))
{
$RemAzPublicIP | Select-Object Name,ResourceGuid
}
Else
{
ForEach($pi in $RemAzPublicIP)
{
if ($pscmdlet.ShouldProcess("Deleting NetworkInterface $($pi.Name)"))
{
Write-Output "Removing Public IP Address without Virtual Machine association: $($pi.Name)"
Remove-AzureRmPublicIpAddress -Name "$($pi.name)" -ResourceGroupName $ResourceGroup
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name Name -Value $($pi.Name)
$object | Add-Member -MemberType NoteProperty -Name ResourceGuid -Value $($pi.ResourceGuid)
$removed += $object
}
}
}
}
End
{
# List the removed objects
$removed
}
2
Answers
You can utilise
Get-AzNetworkInterface
to return all NICs within your current context.You would have to filter the results to see which were not attached to a virtual machine.
If you have a lot of resources to check then you could use
Search-AzGraph
from theAz.ResourceGraph
module to perform the search.Once you have those results and validated it’s correct you can then use
Remove-AzNetworkInterface
to delete.Microsoft has dedicated document to handle it – https://learn.microsoft.com/en-us/previous-versions/azure/virtual-machines/linux/find-unattached-nics
Note that Microsoft doesn’t pay attention to NICs attached to private endpoints that can part of other resource, they only talking about "unattached network interface cards (NICs) for Azure VMs".
Therefore I added reference to ‘privateEndpoint’ as well
You can add it to Microsoft code and make the deletion automatic, I decided to do it manual and don’t take risks, so used the following to list those nics:
or for better output view