I had a previous customer shoot me an email asking for help whipping up a script to convert a list of IP addresses from a text file to their respective host names, and put that into another text file. I put together a little demonstration script to show a way to get this done. I am using the .Net Static Class “system.net.DNS”. I hope this is useful to someone :)
# The following line read a plain list of IPs from files. For this demo, I have
# this line commented out and added a line to just define an array of IPs here
#$listofIPs = Get-Content c:\IPList.txt
$listofIPs = "184.108.40.206","220.127.116.11","18.104.22.168"
#Lets create a blank array for the resolved names
$ResultList = @()
# Lets resolve each of these addresses
foreach ($ip in $listofIPs)
$result = $null
$currentEAP = $ErrorActionPreference
$ErrorActionPreference = "silentlycontinue"
#Use the DNS Static .Net class for the reverse lookup
# details on this method found here: http://msdn.microsoft.com/en-us/library/ms143997.aspx
$result = [System.Net.Dns]::gethostentry($ip)
$ErrorActionPreference = $currentEAP
$Resultlist += [string]$Result.HostName
$Resultlist += "$IP - No HostNameFound"
# If we wanted to output the results to a text file we could do this, for this
# demo I have this line commented and another line here to echo the results to the screen
#$resultlist | Out-File c:\output.txt
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm.
Thank you for posting this. But for some reason when I use the file name option(i un-commented it out), it doesn't seem to resolve the IP address. All it does it spit back out the IP's and says "No HostnameFound" Put if I enter each IP in the script it works like a charm. Can you help?