Wednesday, 24 June 2015

Powershell : Resolve Hostname from IP address and vice versa

In this article, I am going to write powershell script to find machinename from IP address and get IP address from computer name. We can resolve hostname from IP address and vice versa by using .NET class System.Net.Dns.

Find machine name from IP address:

$ipAddress= ""

Resolve Hostname to IP Address:

$machineName= "DC1"
$hostEntry= [System.Net.Dns]::GetHostByName($machineName)

Resolve Hostname for set of IP addresses from text file:

Use the below powershell script to find machine name for multiple IP addresses. First create the text file ip-addresses.txt which includes one IP address in each line. You will get the machinename list in the txt file machinenames.txt.
Get-Content C:\ip-addresses.txt | ForEach-Object{
$hostname = ([System.Net.Dns]::GetHostByAddress($_)).Hostname
if($? -eq $True) {
  $_ +": "+ $hostname >> "C:\machinenames.txt"
else {
   $_ +": Cannot resolve hostname" >> "C:\machinenames.txt"

Find Computer name for set of IP addresses from CSV:

Use the below powershell script to get hostname for multiple IP addresses from csv file. First create the csv file ip-addresses.csv which includes the column IPAddress in the csv file. You will get the hostname and IP address list in the csv file machinenames.csv.
Import-Csv C:\ip-Addresses.csv | ForEach-Object{
$hostname = ([System.Net.Dns]::GetHostByAddress($_.IPAddress)).Hostname
if($? -eq $False){
$hostname="Cannot resolve hostname"
New-Object -TypeName PSObject -Property @{
      IPAddress = $_.IPAddress
      HostName = $hostname
}} | Export-Csv C:\machinenames.csv -NoTypeInformation -Encoding UTF8


1 comment:

  1. Thank you! Finally a simple solution.