Resolve IP-Addresses

This one-liner accepts one or more IP-addresses and will try to resolve the address. If DNS returns valid information, you will receive the host name and aliases. If not, you will get a warning with the cause:

'127.0.0.1', '127.0.0.2', '10.10.10.11' | `
Foreach-Object { $ip = $_; `
try { [System.Net.DNS]::GetHostByAddress($_) } `
catch { Write-Warning "Unable to resolve $ip. Reason: $_" } }

To analyze a network segment, you should try something like this (adjust the IP segment to match yours):

1..255 | Foreach-Object { "192.168.1.$_" } | `
Foreach-Object { $ip = $_; `
try { [System.Net.DNS]::GetHostByAddress($_) } catch `
{
Write-Warning "Unable to resolve $ip. Reason: $_" } }

 

Twitter This Tip! ReTweet this Tip!


Posted Mar 22 2011, 08:00 AM by ps1

Comments

G.W. Scheppink wrote re: Resolve IP-Addresses
on 04-01-2011 7:25 AM

Hi ps1,

I like your tip but this one takes ages to complete, even on a small subnet. A while ago I found the following which does a very good job: In my home network where I keep DNS up-to-date via the HOSTS file it works like charm.  The source should be quite familiar powershell.com/.../finding-systems-online-fast.aspx  

and the other function is derived from dmitrysotnikov.wordpress.com/.../03

Just combined the things to something more useful.

****************************

function Get-ComputerNameByIP {

param(

     $IPAddress = $null

     )

BEGIN { }

PROCESS {

     if ($IPAddress -and $_) {

     throw ‘Please use either pipeline or input parameter’

     break

     } elseif ($IPAddress) {

           ([System.Net.Dns]::GetHostbyAddress($IPAddress))

     } elseif ($_) {

           trap [Exception] {

           write-warning $_.Exception.Message

           continue;

           }

           [System.Net.Dns]::GetHostbyAddress($_)

     } else {

           $IPAddress = Read-Host “Please supply the IP Address”

           [System.Net.Dns]::GetHostbyAddress($IPAddress)

     }

}

END { }    

} # End function

function Check-Online {

param(

     $computername

     )

     test-connection -count 1 -ComputerName $computername -TimeToLive 5 -asJob |

     Wait-Job |

     Receive-Job |

     Where-Object { $_.StatusCode -eq 0 } |

     Select-Object -ExpandProperty Address StatusCode

}

# This code pings an IP segment from 192.168.1.1 to 192.168.1.254 and returns only those IPs that respond.

CLS

$Start = Get-Date

$ips = 1..254 | ForEach-Object { "192.168.6.$_" }

$online = Check-Online -computername $ips

$online

foreach ($PC in $online) {

     Get-ComputerNameByIP $PC

}

$End = Get-Date

Write-Host "`nStarted at: " $Start

Write-Host "Ended at: " $End

Copyright 2012 PowerShell.com. All rights reserved.