Finding Location of IP Address

Most IP addresses can be located using web services. Here is a very simple function that takes an IP address and returns information about its location:

#requires -Version 3.0

function Get-IPLocation([Parameter(Mandatory)]$IPAddress)
    Invoke-RestMethod -Method Get -Uri "$IPAddress" |
      Select-Object -ExpandProperty Country -Property City, IP, Location 

This example also illustrates how you can use Select-Object with both -Property and –ExpandProperty parameters to move some nested properties up to parent level.

Let’s find out where Googles DNS lives:

PS C:\> Get-IPLocation -IPAddress

name     : United States
code     : US
city     : Mountain View
ip       :
location : @{accuracy_radius=1000; latitude=37,386; longitude=-122,0838; time_zone=America/Los_Angeles} 

And here is how you can resolve any hostname to an IP address, for example, the famous

PS> [Net.Dns]::GetHostByName('').AddressList.IPAddressToString

So if you wanted to know where that IP is located, add this:

PS> Get-IPLocation -IPAddress

name     : United States
code     : US
city     : New York
ip       :
location : @{accuracy_radius=1000; latitude=40,7143; longitude=-74,006; 

(of course this is just where the server sits, not Aleksandar or Ravi or all the other fine editors  )

Twitter This Tip! ReTweet this Tip!