Warning: Undefined array key "oxygen-cache-1409" in /var/www/wordpress_jb/wp-content/plugins/jetpack/class.jetpack.php on line 5759

Warning: Undefined array key "oxygen-cache-1414" in /var/www/wordpress_jb/wp-content/plugins/jetpack/class.jetpack.php on line 5759

Warning: Undefined array key "oxygen-universal-styles" in /var/www/wordpress_jb/wp-content/plugins/jetpack/class.jetpack.php on line 5759

Finding Active IP Addresses and Resolved Hostnames with PowerShell

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;
}

3 comments on “Finding Active IP Addresses and Resolved Hostnames with PowerShell”

About JB

I've been a technologist for over 20 years, getting my start in IT with a large Fortune 100 international retailer in the 1990s. I love to talk about new technology, mobile devices, software development, photography, and the weather.  The opinions expressed on this blog are my own.

Follow me

Copyright © Justin Braun.  All rights reserved.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
%d bloggers like this: