Question:
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.
1 2 3 4 5 |
$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.
Answer:
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,
1 2 3 4 5 6 7 8 |
$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 } } |