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 "http://geoip.nekudo.com/api/$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 8.8.8.8 name : United States code : US city : Mountain View ip : 8.8.8.8 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 powershellmagazine.com:
PS> [Net.Dns]::GetHostByName('powershellmagazine.com').AddressList.IPAddressToString 104.131.21.239
So if you wanted to know where that IP is located, add this:
PS> Get-IPLocation -IPAddress 104.131.21.239 name : United States code : US city : New York ip : 104.131.21.239 location : @{accuracy_radius=1000; latitude=40,7143; longitude=-74,006; time_zone=America/New_York}
(of course this is just where the server sits, not Aleksandar or Ravi or all the other fine editors )