Get Azure VNET private IPs which are in use

In my previous article I showed you how to set IP restirctions on WebApp. Today I want to show you how to get Azure VNET private IPs which are in use.

Recently I was looking for PowerShell script which will help me to find VNET IPs which are already in use.
The only command which I found was Test-AzureRmPrivateIPAddressAvailability. Unfortunately command can only check if specific IP address is available or not.

Function which I prepared list all IPs from all subnets assigned to Azure VNET. It can be very usefull when for example you want to add virtual machine to some subnet, but you don’t know which IPs are available.

Script:
function Get-AzureVNETPrivateIPs {

    Param(
        [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Vnet name", ValueFromPipeline = $false)] 
        $Vnet,
        [Parameter(Position = 1, Mandatory = $true, HelpMessage = "Resource group name", ValueFromPipeline = $false)] 
        $ResourceGroupName
    )
              
    If (!(Get-AzureRmContext)) {
        Write-Host "Please login to your Azure account"
        Login-AzureRmAccount
    }
    Try {
        $Subnets = (Get-AzureRmVirtualNetwork -Name $Vnet -ResourceGroupName $ResourceGroupName).SubnetsText 
    }
    Catch {
        Write-Error "VNET $Vnet can not be found!"
        break
    }

    $Subnets = $Subnets | ConvertFrom-Json
    foreach ($subnet in $subnets) {
        if ($subnet.IpConfigurations -ne $null) {
            $NotAvailableIPs = @()
            foreach ($ipconfig in $subnet.IpConfigurations) {
                $RG = $ipconfig.Id.Split("/")[4]
                $NIC = $ipconfig.Id.Split("/")[8]
                $IP = (Get-AzureRmNetworkInterface -Name $NIC -ResourceGroupName $RG).IpConfigurations.PrivateIpAddress
                $NotAvailableIPs += $IP
            }
            $SubnetName = $subnet.Name
            $AddressPrefix = $subnet.AddressPrefix
            $IPsUsed = $NotAvailableIPs.Count
            Write-Host "Subnet $subnetname ($AddressPrefix) have $IPsUsed IPs which are already used:"
            foreach ($NotAvailableIP in $NotAvailableIPs) {
                Write-Host $NotAvailableIP
            }
            Write-Host "-----------------------------------"
        }

    }
}
Example of usage:
Get-AzureVNETPrivateIPs -Vnet testVnet -ResourceGroupName rgnetworktest

In one of the next articles I will share with you function which will work in similar way. Instead of get Azure VNET private IPs which are in use it will list IPs which can be assigned to new resource in Azure :).

I hope it will be usefull for some of you 😉
Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *