Finding Active IP Addresses and Resolved Hostnames with PowerShell

By: Justin Braun
Posted on: December 17, 2008

Ever wanted to know what IP addresses are being used on a particular subnet and what each IP address resolves to which hostname, if any?  This script accomplishes just that.

# Continue to run script when an error occurs
$ErrorActionPreference = "SilentlyContinue"
 
# Process through the loop of IP addresses 1-254
1..254 | foreach -Process `
{
    # We're combining the contents of different objects, so create our own
    $obj = New-Object PSObject;
    
    # Perform the Ping using WMI
    $ping = get-WmiObject -Class Win32_PingStatus -Filter ("Address='10.10.2." + $_ + "'");
    
    # Put the IP Address into our object
    $obj | Add-Member NoteProperty IPAddress($ping.Address);
    
    # Take the Ping Status Code that is returned (0 = pingable)
    $obj | Add-Member NoteProperty StatusCode($ping.StatusCode);
      
    # If we can ping the address, let's try to resolve the hostname
    if($ping.StatusCode -eq 0)
    {
          # Record that the ping was successful
           $obj | Add-Member NoteProperty Status("Online");
        
        # Try to resolve the IP address to a hostname in DNS
        $dns = [System.Net.Dns]::GetHostByAddress($ping.Address);
        
           if($dns -ne $null)
           {
            # Add the resolved hostname to our collection
             $obj | Add-Member NoteProperty ResolvedHostName($dns.HostName);
           }
           else
           {
            # Couldn't resolve the IP address to a hostname
               $obj | Add-Member NoteProperty ResolvedHostName("");
           }
    }
    else
    {
        # Can't ping IP address, so mark host as offline
           $obj | Add-Member NoteProperty ResolvedHostName("");
           $obj | Add-Member NoteProperty Status("Offline");
    }
      
    # Write the collection out
    Write-Output $obj;
    
    # Cleanup DNS object
    $dns = $null;
}

Related Articles

Compellent PSCS One-Liner Coding: Tip #1

The Compellent Storage Center provides in-depth reporting, alerting, and monitoring as part of the p
Posh1

PowerShell Scripting Options for Dell Storage

Back in 2008, Compellent released their first iteration of the PowerShell Command Set.

Using Powershell To Generate Test Mailboxes

There are situations where you may want to generate a number of test mailboxes whether it be for a d