5

I am new to Powershell scripting and I need to write one script. I have a list of server hostnames and I need to get IP addresses of those servers and write the results in a file.

The hostnames are one column in Excel spreadsheet but I can format them into anything (csv, simple txt file with one hostname per line etc.).

I would like to format the output the way there is a hostname of the server and its IP address per line (so there are multiple lines in case the server has more than one IP).

So far I have been using the simple text file with hostname per line, but from the output in PS I am unable to distinguish what server the IP address is for.

$servers = get-content "path_to_the_file" 
foreach ($server in $servers) {
[System.Net.Dns]::GetHostAddresses($server)
}

So I was wondering about loading the hostnames from csv file and printing the hostnames and related IP addresses to another csv again, but I am unsure how.

I am investigating the possibility to capture the required information (hostname and IP) by running nslookup $server in foreach.

Could someone give me a hand?

Thank you.

Ondrej Lebl
  • 51
  • 1
  • 1
  • 2
  • If you're using PowerShell 5 or later on Windows 8/2012 or later, the `Resolve-DnsName` command is available. – Bacon Bits Oct 19 '18 at 12:58

4 Answers4

11

Combining hostnames to addresses can be done within the loop. As a host can have multiple IP addresses, you need to take that into accout too. This will create another a loop. Like so,

$servers = get-content "path_to_the_file"
foreach ($server in $servers) {
  $addresses = [System.Net.Dns]::GetHostAddresses($server)
  foreach($a in $addresses) {
    "{0},{1}" -f $server, $a.IPAddressToString
  }
}
vonPryz
  • 22,996
  • 7
  • 54
  • 65
3

This will display "IP cannot resolve" if there is no DNS record.

$servers = get-content "path_to_the_file"e
foreach ($Server in $Servers)
{
    $Addresses = $null
    try {
        $Addresses = [System.Net.Dns]::GetHostAddresses("$Server").IPAddressToString
    }
    catch { 
        $Addresses = "Server IP cannot resolve."
    }
    foreach($Address in $addresses) {
        write-host $Server, $Address 
    }
}
blld
  • 1,030
  • 10
  • 19
Chu
  • 41
  • 1
1

You can also use nslookup in a Foreach-object loop with 'get-ADcomputer' cmdlet, assuming you have a consistent naming convention / computers are in AD.

The 'Select-Object -unique' does a nice job of stripping out all but one instance of the DC that was queried in the results.

get-adcomputer -Filter {name -like 'nameOfComputer*'} | ForEach-Object 
{nslookup $_.name} | Select-Object -Unique
0

I just used the cmdlet provided by "Nicholas Leader".

It returned a response with every IP address for each machine that starts with XX-

Kudos!

get-adcomputer -Filter {name -like 'XX-*'} | ForEach-Object {nslookup $_.name} | Select-Object -Unique  
ShanayL
  • 1,217
  • 2
  • 14
  • 29