Getting IP addresses for hostnames using nslookup in Powershell

我只是一个虾纸丫 提交于 2019-12-06 06:33:12

问题


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.


回答1:


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
  }
}



回答2:


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 
    }
}



回答3:


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



回答4:


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  


来源:https://stackoverflow.com/questions/18102227/getting-ip-addresses-for-hostnames-using-nslookup-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!