Using PowerShell to resolve Host names to IP address

Today's post is to be a quick one, more like a useful DevOps tip. Today, I was given a list of hosts that I had to resolve to IP addresses in order to add them to a config file. Obviously there are a few ways to do this, but I wanted to automate it because you never know when someone will request something similar.

Powershell to the rescue then. The script is pretty simple and I bet that it can be condenced even more, but I like my code and scripts as readable as possible. It is handy to remember that not everyone in your team is a PowerShell guru, so keeping things simple means that other developers are more likely to adopt and enhance your scripts scripts rather than avoid using them in case they break something they don't understand.

I've attached the script below for your perusal:

[string[]] $hosts = "host1", "host2", "etc" 

$ips = ""
foreach ($myhost in $hosts)
{
    try
    {
        $ipaddress = [System.Net.Dns]::GetHostAddresses($myhost)
        write-host "Mapped " + $myhost + " to -> " + $ipaddress
        if ([string]::IsNullOrEmpty($ips))
        {
            $ips = $ipaddress 
            continue;
        }
        $ips = $ips + "," + $ipaddress
    }
    catch
    {
        write-host $_
    }
}
write-host $ips

Before running it, make sure you configure the list of host names i.e. $hosts at the top of the script. Optionally, if you have a large number of host names, you could configure the script to read hosts names from a file, but I will leave this as an exercise for the reader.

Feel free to use the comments below to let me know if you found this script useful or need help with anything.