PowerShell: Scan a Subnet for Used and Unused IPs

A newer version of this script is available here.

function scanForAvailableIPs{
    param(
        $cidrBlock=$(
                $interfaceIndex=(Get-WmiObject -Class Win32_IP4RouteTable | where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} |  Sort-Object metric1).interfaceindex;
                $interfaceObject=(Get-NetIPAddress -InterfaceIndex $interfaceIndex -AddressFamily ipv4|select IPAddress,PrefixLength)[0];
                "$($interfaceObject.IPAddress)/$($interfaceObject.PrefixLength)"),
        $limit=65536 # Assuming CIDR /16
        )

    function Get-IPrange{
        <# This Get-IPrange function has been obtained at https://gallery.technet.microsoft.com/scriptcenter/List-the-IP-addresses-in-a-60c5bb6b
        Snippet Author: BarryCWT
        .SYNOPSIS  
        Get the IP addresses in a range 
        .EXAMPLE 
        Get-IPrange -start 192.168.8.2 -end 192.168.8.20 
        .EXAMPLE 
        Get-IPrange -ip 192.168.8.2 -mask 255.255.255.0 
        .EXAMPLE 
        Get-IPrange -ip 192.168.8.3 -cidr 24 
        #> 
 
        param ( 
        [string]$start, 
        [string]$end, 
        [string]$ip, 
        [string]$mask, 
        [int]$cidr 
        ) 
 
        function IP-toINT64 () { 
            param ($ip) 
 
            $octets = $ip.split(".") 
            return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3]) 
        } 
 
        function INT64-toIP() { 
            param ([int64]$int) 

            return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
        } 
 
        if ($ip) {$ipaddr = [Net.IPAddress]::Parse($ip)} 
        if ($cidr) {$maskaddr = [Net.IPAddress]::Parse((INT64-toIP -int ([convert]::ToInt64(("1"*$cidr+"0"*(32-$cidr)),2)))) } 
        if ($mask) {$maskaddr = [Net.IPAddress]::Parse($mask)} 
        if ($ip) {$networkaddr = new-object net.ipaddress ($maskaddr.address -band $ipaddr.address)} 
        if ($ip) {$broadcastaddr = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $maskaddr.address -bor $networkaddr.address))} 
 
        if ($ip) { 
            $startaddr = IP-toINT64 -ip $networkaddr.ipaddresstostring 
            $endaddr = IP-toINT64 -ip $broadcastaddr.ipaddresstostring 
        } else { 
            $startaddr = IP-toINT64 -ip $start 
            $endaddr = IP-toINT64 -ip $end 
        } 
 
 
        for ($i = $startaddr; $i -le $endaddr; $i++) 
        { 
            INT64-toIP -int $i 
        }

    }

    # Regex values
    $regexIP = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    $regexCidr=[regex] "\/(.*)"
    $regexFourthOctetValue=[regex] ".+\..+\..+\.(.+)"

    # Value Extractions
    $ip=$regexIP.Matches($cidrBlock).Value
    $cidr=$regexCidr.Matches($cidrBlock).Groups[1].Value
    $allIPs=Get-IPrange -ip $ip -cidr $cidr
    

    # Remove fourth octet values matching 0,1, and 255
    if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 0){$first, $rest= $allIPs; $allIPs=$rest;}
    if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 1){$first, $rest= $allIPs; $allIPs=$rest;}    
    if($regexFourthOctetValue.Matches($allIPs[$allIPs.length-1]).Groups[1].Value -eq 255){$allIPs = $allIPs | ? {$_ -ne $allIPs[$allIPs.count-1]}}

    # Display sweep scanning output
    #$allIPs | ForEach-Object {if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){$_}}

    # Collect unpingable IPs
    "Collecting available IPs. Please wait awhile..."
    $availableIPs=@()
    $count=0
    $allIPs|%{$pingable=Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0";
                if($pingable){
                    write-host "$_ is pingable"
                    $availableIPs+=,$_
                    $count++
                    }
                if($count -ge $limit){break}
                }
    return $availableIPs
    # Also, export unavailableIPs just because I can
    #$GLOBAL:unavailableIPs=Compare-Object $allIPs $availableIPs -PassThru
}

scanForAvailableIPs -limit 10
Script:
function scanForAvailableIPs{
param(
$cidrBlock=$(
$interfaceIndex=(Get-WmiObject -Class Win32_IP4RouteTable | where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} | Sort-Object metric1).interfaceindex;
$interfaceObject=(Get-NetIPAddress -InterfaceIndex $interfaceIndex|select IPAddress,PrefixLength)[0];
"$($interfaceObject.IPAddress)/$($interfaceObject.PrefixLength)";
)
)

function Get-IPrange{
<# This Get-IPrange function has been obtained at https://gallery.technet.microsoft.com/scriptcenter/List-the-IP-addresses-in-a-60c5bb6b
Snippet Author: BarryCWT
.SYNOPSIS
Get the IP addresses in a range
.EXAMPLE
Get-IPrange -start 192.168.8.2 -end 192.168.8.20
.EXAMPLE
Get-IPrange -ip 192.168.8.2 -mask 255.255.255.0
.EXAMPLE
Get-IPrange -ip 192.168.8.3 -cidr 24
#>

param (
[string]$start,
[string]$end,
[string]$ip,
[string]$mask,
[int]$cidr
)

function IP-toINT64 () {
param ($ip)

$octets = $ip.split(".")
return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3])
}

function INT64-toIP() {
param ([int64]$int)

return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
}

if ($ip) {$ipaddr = [Net.IPAddress]::Parse($ip)}
if ($cidr) {$maskaddr = [Net.IPAddress]::Parse((INT64-toIP -int ([convert]::ToInt64(("1"*$cidr+"0"*(32-$cidr)),2)))) }
if ($mask) {$maskaddr = [Net.IPAddress]::Parse($mask)}
if ($ip) {$networkaddr = new-object net.ipaddress ($maskaddr.address -band $ipaddr.address)}
if ($ip) {$broadcastaddr = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $maskaddr.address -bor $networkaddr.address))}

if ($ip) {
$startaddr = IP-toINT64 -ip $networkaddr.ipaddresstostring
$endaddr = IP-toINT64 -ip $broadcastaddr.ipaddresstostring
} else {
$startaddr = IP-toINT64 -ip $start
$endaddr = IP-toINT64 -ip $end
}


for ($i = $startaddr; $i -le $endaddr; $i++)
{
INT64-toIP -int $i
}

}

# Regex values
$regexIP = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
$regexCidr=[regex] "\/(.*)"
$regexFourthOctetValue=[regex] ".+\..+\..+\.(.+)"

# Value Extractions
$ip=$regexIP.Matches($cidrBlock).Value
$cidr=$regexCidr.Matches($cidrBlock).Groups[1].Value
$allIPs=Get-IPrange -ip $ip -cidr $cidr

# Remove fourth octet values matching 0,1, and 255
if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 0){$first, $rest= $allIPs; $allIPs=$rest;}
if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 1){$first, $rest= $allIPs; $allIPs=$rest;}
if($regexFourthOctetValue.Matches($allIPs[$allIPs.length-1]).Groups[1].Value -eq 255){$allIPs = $allIPs | ? {$_ -ne $allIPs[$allIPs.count-1]}}

# Display sweep scanning output
#$allIPs | ForEach-Object {if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){$_}}

# Collect unpingable IPs
"Collecting available IPs. Please wait awhile..."
$GLOBAL:availableIPs=$allIPs | ForEach-Object {if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){$_}}

# Also, export unavailableIPs just because I can
$GLOBAL:unavailableIPs=Compare-Object $allIPs $availableIPs -PassThru
}


scanForAvailableIPs;
"`r`nAvailable IPs:`r`n------------------------------------------------`r"
$availableIPs;

"`r`nUnavailable IPs:`r`n------------------------------------------------`r"
$unavailableIPs;
Sample Output:
Available IP:
------------------------------------------------

192.168.10.2
192.168.10.3
192.168.10.4
192.168.10.5
-- Omitted for brevity --
192.168.10.250
192.168.10.251
192.168.10.252
192.168.10.253
192.168.10.254


Unavailable IP:
------------------------------------------------

192.168.10.51
192.168.10.52
192.168.10.102
192.168.10.103

Leave a Reply

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