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:
[cc lang=”powershell”]
Function Get-HostName ([string]$ipAddress) {
New-Object psobject -Property @{
IPAddress = $ipAddress
HostName = try { [system.net.dns]::GetHostByAddress($ipAddress).HostName } catch { “UNKNOWN” }
}
}
[/cc]

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:
[cc lang=”powershell”]
Get-Content ipList.txt |
%{ Get-HostName $_ } |
Export-Csv MyIPsExport.csv -NoTypeInformation
[/cc]

This entry was posted in Scripting. Bookmark the permalink.

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

  1. Pingback: Do you have any way of getting IPs from a list of server names? | EnterpriseAdmins.org

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.