Dan Lewis
Dan Lewis

Reputation: 33

Import list of IP addresses, resolve their hostnames, export IP and hostname to spreadsheet

Complete powershell noob here. I am attempting to do the following:

  1. Import a list of IP addresses from a text file.
  2. Obtain the hostname of each IP address. If unable to, provide the failure reason.
  3. Export both IP address and hostname (or error) line by line in a CSV.

I was attempting to use the following script however I do not know what IP address is which since there are some errors:

get-content .\dnsip.txt | ForEach-Object {([system.net.dns]::GetHostByAddress($_)).hostname

Can someone help me write a script that would do this?

Thanks!

Upvotes: 2

Views: 5854

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You can do the following:

Get-Content .\dnsip.txt | ForEach-Object {
    $obj = "" | Select-Object IPAddress,Hostname
    try { 
        $obj.Hostname = ([system.net.dns]::GetHostByAddress($_)).hostname
    } catch { 
        $obj.Hostname = 'Unknown Host'
    } 
    $obj.IPAddress = $_
    $obj
} | Export-Csv -Path Output.csv -NoType

Explanation:

During each iteration, a new object $obj is created with two properties, IPAddress and Hostname, set as empty strings. A try {} block is used to attempt to retrieve the Hostname value using your method. If it succeeds, Hostname will be assigned the value returned by the command. If that throws an exception, it will be caught by the catch {} block. In side catch {}, the Hostname property is given a value of Unknown Host. Then IPAddress is assigned the current item processed ($_) from your Get-Content.

All custom objects are exported to Output.csv via Export-Csv. The -NoType switch prevents data type information from being printed at the top of the CSV file.

Upvotes: 4

Related Questions