PowerShell: Scan subnet for dead addresses

Quick script to scan a range of addresses on an IPv4 subnet and report ones that don’t ping, additionally doing a reverse DNS query on those IP addresses to try and get their names.

I’m doing two pings, as I found that when only doing one I got a lot of false positives. The reverse DNS query slows things down quite a bit so comment that out if you don’t need it.

$Subnet = "164.11.249"
$MinAddress = 47
$MaxAddress = 254
# step through each address from MinAddress to MaxAddress
for($Address=$MinAddress;$Address -le $MaxAddress;$Address++){
    # make a text string for the current IP address to be tested
    $TestAddress = $Subnet+"."+[convert]::ToString($Address)
    # do the ping(s), don't display red text if the ping fails (erroraction)
    $Result = Test-Connection -ComputerName $TestAddress -Count 2 -ErrorAction SilentlyContinue
    if($Result -eq $null){
        Write-Host "No reply from $TestAddress" -NoNewline
        # have to use try/catch as the GetHostByAddress errors in a nasty way if it doesn't find anything
        try{
            # do the reverse DNS query
            $HostName = [System.Net.Dns]::GetHostByAddress($TestAddress).HostName
            if($HostName -ne $null){
                # found something in DNS, display it
                Write-Host " ($HostName)"
            }
        } catch {
            # didn't find anything (GetHostByAddress generated an error), just do a CRLF
            write-host ""
        }
    }
}

This script demonstrates the use of reverse DNS queries, a try catch statement, and converting integers to strings.

This entry was posted in PowerShell and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s