PowerShell: Finding host name from IP address

In tech support, resolving IP addresses to host names can be something you do on a relatively frequent basis. While I’ve always used the CLI ping command with the -a option, I have also been working towards higher proficiency in PowerShell. Frankly, for a single IP address, I prefer sticking with CLI. When working with a number of addresses, however, it gets a lot more interesting.

Start out by creating a text file – e.g. AddressesToResolve.txt, and store it somewhere that you have write permissions. Next, open PowerShell (I prefer the ISE, but you do you), and run the following command:

Get-Content 'C:\folder\AddressToResolve.txt' | ForEach-Object{
$hostname = ([System.Net.Dns]::GetHostByAddress($_)).Hostname
if($? -eq $True) {
$_ +": "+ $hostname >> "C:\folder\Host names.txt"
}
else {
$_ +": Cannot resolve hostname" >> "C:\folder\Host names.txt"
}}

First, the script imports the contents of the text file, which it then evaluates. If it gets a host name, it adds that to a new text file, and if it doesn’t get a host name, it adds “Cannot resolve hostname” to the same file. The result looks something like this:

195.58.42.67: Hostname1.dom.tl
195.58.56.184: Hostname2.dom.tl
195.28.2.67: Cannot resolve hostname


Posted

in

, ,

by

Comments

By posting a comment, you consent to our collecting the information you enter. See privacy policy for more information.

This site uses Akismet to reduce spam. Learn how your comment data is processed.