update ipaddresses to hostnames in existing csv

Hi there, what I’d like to achieve is the following: I’ve an csv report with a column of ipaddresses. I’d like to resolve all the ipaddresses to hostnames and update the existing report with that information.

 

So far I’ve written this what gives me only the list with host names…:

$data = Import-Csv "C:\temp\test.csv"| Select-Object "Host"
ForEach ($item in $data)
{
$impactedhost = $item.("Host")
Resolve-DnsName -Name $impactedhost -Server 8.8.8.8 |select NameHost

}

When I do a |export-csv afterwards I only get only the column of host names…

What should I do next?

 

Thanks in advance

 

That should be enough actually …

Import-Csv -Path ‘C:\temp\test.csv’ |
Select-Object -Property *,@{
Name = ‘HostName’;
Expression = { Resolve-DnsName -Name $_.Host -Server 8.8.8.8 | Select-Object -ExpandProperty NameHost }
}

… untested … and depending on the amount of hosts that could take a while … :wink:

You’re really close.

 

Also, wrap your code in

 tags, it makes it more readable.

Once you have the IP, you want to pipe it to export-csv (or even add-content to blah.csv). I tend to NOT want to add to the original file in case something goes wrong. Something like this will work:

 

ForEach ($item in $data)
{
$ip=(Resolve-DnsName $item |? {$_.type -eq "A"}).ipaddress
"$item,$ip" |add-content "C:\test\test3.csv"
}

Great! Thanks all for suggestions!

[quote quote=166669]That should be enough actually …

PowerShell
5 lines
 
1
2
3
4
5
Import-Csv -Path 'C:\temp\test.csv' |
Select-Object -Property *,@{
Name = 'HostName';
Expression = { Resolve-DnsName -Name $_.Host -Server 8.8.8.8 | Select-Object -ExpandProperty NameHost }
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
... untested ... and depending on the amount of hosts that could take a while ... 😉

[/quote]

This one does basically the trick but doesn’t update the csv sheet though…

I wanted to leave some space for you to shine. :wink: … my code example is meant as a suggestion - feel free to tweak it to your needs. You could assign the whole code snippet to a variable and export it to a new CSV file or - if you like - to the same CSV file using the parameter -Force.

That’s the whole idea…

[/quote]

[quote quote=166675][/quote]

 

DNS name contains an invalid character
At line:4 char:6

  • $ip=(Resolve-DnsName $item |? {$_.type -eq “A”}).ipaddress