ComputerPowerShellTech Tips

PowerShell Code – Hostname to IP Address

Here is some PowerShell code that will convert hostnames to IP addresses. It will read from a text file and output to a CSV.

The best thing about this script is that it will lookup all resolvable IP’s for a given hostname, as many URL’s will have multiple IP addresses associated to them.

In the output you will get the URL, the resolved IP address(s) and what the IP address actually resolves to. It will also show you the ping status, such as “Host Online” or “Request Timed Out” or “NoDNS”.

Example output CSV from the script

As the script is running it will error and addresses it cant resolve, this is expected behavior, it will also show a progress bar. We tested this with a text file with 5000 URL’s and it worked fine.

Hostname to IP script in progress

Here is the PowerShell script :-

$counter = 1
$comps = get-content C:\TEMP\url-list.txt
$dnsResults = "C:\TEMP\url-output.csv"

function get-dnsres{
foreach ($comp in $comps) {
$TempIP = ([system.net.dns]::GetHostAddresses($comp)) | select IPAddressToString

$status = "Processing system {0} of {1}: {2}" -f $counter,$comps.Count,$comp
Write-Progress 'Resolving DNS' $status -PercentComplete ($counter/$comps.count * 100)
$counter++
$comp |
select @{Name='ComputerName';Expression={$comp}}, `
@{Name='ResolvesToIP';Expression={[system.net.dns]::GetHostAddresses($comp)}}, `
@{Name='IPResolvesTo';Expression={([system.net.dns]::GetHostEntry($TempIP.IPAddressToString)).HostName}}, `
@{Name='PingStatus'; Expression={ `
if ((get-wmiobject -query "SELECT * FROM Win32_PingStatus WHERE Address='$comp'").statuscode -eq 0) {'Host Online'} `
elseif ((get-wmiobject -query "SELECT * FROM Win32_PingStatus WHERE Address='$comp'").statuscode -eq 11003) {'Destination Host Unreachable'} `
elseif ((get-wmiobject -query "SELECT * FROM Win32_PingStatus WHERE Address='$comp'").statuscode -eq 11010) {'Request Timed Out'} `
elseif ((get-wmiobject -query "SELECT * FROM Win32_PingStatus WHERE Address='$comp'").statuscode -eq $Null) {'NoDNS'}
}
}
}
}

get-dnsres | export-csv $dnsResults -notypeinformation
invoke-item $dnsResults

Duncan

Duncan is a technology professional with over 20 years experience of working in various IT roles. He has a interest in cyber security, and has a wide range of other skills in radio, electronics and telecommunications.

One thought on “PowerShell Code – Hostname to IP Address

  • This script is amazing. Thank you so much, it is extremely useful for me.

    Reply

Leave a Reply

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