'How to find and Delete orphan public ip in azure using powershell
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
}
Solution 1:[1]
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.
# This will return NICs which aren't associated to a VM
$orphanedNics = Get-AzNetworkInterface | Where-Object VirtualMachine -eq $null
If you have a lot of resources to check then you could use Search-AzGraph from the Az.ResourceGraph module to perform the search.
$query = '
Resources
| where type has "microsoft.network/networkinterfaces"
| where properties !has "virtualmachine"'
$orphanedNics = Search-AzGraph -Query $query
Once you have those results and validated it's correct you can then use Remove-AzNetworkInterface to delete.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrettMiller |
