Last Update: Sep 04, 2024 | Published: Oct 14, 2015
In today’s PowerShell Problem Solver, we’ll wrap up a series of articles that began with a simple request to update a CSV file of computer information with IP addresses.
As I mentioned at the end of the last article, using Test-Connection to resolve a computer name to IP may not always be an option. So instead of asking the computer for its IP address, we’ll ask DNS. I’m going to use the same CSV file of unrevised computer information.
The goal is to get the missing IP addresses so that I can eventually export the data back to a CSV file. If you are running Windows 8.1 or later, then you should have the DNSClient module. Within that module is a cmdlet called Resolve-DnsName, which is very easy to use.
I’m going to assume you will take a few minutes to read cmdlet help for Resolve-DnsName. I did, and I can use it to find the address for CHI-DC02.
I can update an individual entry like this:
I should point out that this command worked with a Netbios name because the computer was online. If I try to use a pure DNS lookup, then it fails. In this situation, I need to provide a fully qualified name. I point this out because even though one of the computers in my list doesn't have an IP address, there is a static entry for it in DNS. But I can only get it with a FQDN. Depending on your situation, you may need to take this into account. In my case, I intend to use a ForEach-Object construct and update any object in my collection that is missing an IP address.
I'm using the –F operator to plug in each computername into the {0} placeholder to build a FQDN. Again, I'm using Write-Host so you can see what is happening. Look at this now: Now I can perform other updates and export to a CSV file as necessary. But what if you don't have the Resolve-DnsName cmdlet? In that case, you'll need to drop down into the .NET Framework and resolve names yourself with the [System.Net.DNS] class. This class has a method called Resolve(). All you need to do is specify a fully qualified host name. It looks like all I need is the AddressList property.
That's not quite right. This looks like a nested object. I bet I can use that IPAddresstoStringProperty.
Yes! That's what I need. Now that I've worked out the commands, I can use ForEach-Object and update my collection of computers.
The output will be very similar to what I did with Resolve-DnsName, and the results are the same.
And I think that about wraps this all up. We started with a simple CSV file but moved beyond that. I hope you are recognizing that instead of trying to manipulate text in a file, I worked with objects in the PowerShell pipeline. Getting data into a text file is pretty easy. But getting the data the way you need it is where the fun lies, and hopefully you've discovered that it doesn't have to be that difficult. As always, comments and questions are welcome.