Do you have any way of getting server name from the attached list of IPs?

Every now and then I get a simple script idea in my email, like this one from a couple weeks ago:

Do you have any way of getting server name from the attached list of IPs?

This is a pretty simple request, and there are probably thousands of possible solutions, but I threw together a quick function that accepts an IP Address as a string and returns the IP address and a host name… like this:

1
2
3
4
5
6
Function Get-HostName ([string]$ipAddress) {
  New-Object psobject -Property @{
    IPAddress = $ipAddress
    HostName = try { [system.net.dns]::GetHostByAddress($ipAddress).HostName } catch { "UNKNOWN" }
  }
}

That’s almost a solution… the only thing remaining would be to read in the text file, call the function for each line and then export the results. That can all be done in one line of code, but I put in some line breaks to make it easier to read:

1
2
3
Get-Content ipList.txt |
%{ Get-HostName $_ } |
Export-Csv MyIPsExport.csv -NoTypeInformation

One comment

  1. […] few days ago, someone asked a very basic question. Where is the opposite version of this script: http://enterpriseadmins.org/blog/scripting/do-you-have-any-way-of-getting-server-name-from-the-attac…? They had a list of host names and wanted the associated IP addresses. Since it is somewhat common […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Notify me of followup comments via e-mail. You can also subscribe without commenting.