[PowerShell snippet] Resolving hostname

Recently I’ve started to embrace PowerShell’s great possibilities, and as a result of that, I’ll post some of my “toys”.

On Unix-like operating system I’m using host command to resolve hostnames into IP’s and the other way. On Windows, there’s a nslookup tool, which works just like the Unix equivalent, but to get accustomed to PowerShell, I’ve decided to write a function, which uses internal command to do NS lookups.

Generally, to resolve a hostname you can use this one-liner:

[System.Net.Dns]::GetHostAddresses("devplant.net")

You can shorten it by declaring a short function.

function resolve( [string] $in ){
   [System.Net.Dns]::GetHostAddresses($in)
}

(Defining functions remember not to collide with pre-existing variable names)

But this is only one-way command – to resolve IP address into a hostname, you have to use other command:

[System.Net.Dns]::GetHostbyAddress("72.21.210.250")

To combine both functionalities, you can extend our function, using regular expression to do a naive recognition of IP addresses.

function resolve( [string] $in ){
	if ($in -match "(\d{1,3}\.){3}(\d{1,3})") {
		[System.Net.Dns]::GetHostbyAddress($in)
	} else {
		[System.Net.Dns]::GetHostAddresses($in)
	}
}

Now here’s how you can use it:

PS C:\Users\leafnode> resolve devplant.net

IPAddressToString : 91.192.224.142
Address           : 2397093979
AddressFamily     : InterNetwork
ScopeId           :
IsIPv6Multicast   : False
IsIPv6LinkLocal   : False
IsIPv6SiteLocal   : False

PS C:\Users\leafnode> resolve 72.21.210.250

HostName                Aliases           AddressList
--------                -------           -----------
210-250.amazon.com      {}                {72.21.210.250}

PS C:\Users\leafnode>

One thought on “[PowerShell snippet] Resolving hostname”

Leave a Reply

Your email address will not be published.