Created
October 23, 2016 20:41
-
-
Save josheinstein/e347e1b0f9740283aaf5d59ed66a2677 to your computer and use it in GitHub Desktop.
Gets location information about the ip address of a local or remote computer by calling a public web service that performs ip geolocation. This function currently only supports IPv4 addresses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#.SYNOPSIS | |
# Gets location information about the ip address of a local or remote computer | |
# by calling a public web service that performs ip geolocation. | |
# This function currently only supports IPv4 addresses. | |
function Get-PublicIP { | |
[CmdletBinding()] | |
param( | |
# The IP address to get location information for. | |
# Leave blank to get the public IP of the machine | |
# running the query. Use the ComputerName parameter | |
# to run the query on a remote computer via remoting. | |
[Parameter(Position=1)] | |
[IPAddress]$IPAddress, | |
# If specified, the lookup is performed on a remote | |
# computer using PowerShell remoting, which must be | |
# properly setup and authenticated. | |
[Parameter()] | |
[String]$ComputerName | |
) | |
process { | |
# Call the IP geolocation IP | |
# If computername was specified, then issue the web request from the | |
# remote computer. | |
$Response = $( | |
$ScriptBlock = { Invoke-RestMethod http://ip-api.com/json/$IPAddress } | |
if ($ComputerName) { Invoke-Command -ComputerName $ComputerName -ScriptBlock $ScriptBlock } | |
else { Invoke-ScriptBlock -ScriptBlock $ScriptBlock } | |
) | |
# If we got a valid response, proceed to reverse DNS | |
if ($Response.query -match "(\d+\.){3}\d+") { | |
# Format the IP address and location of the | |
# response depending on whether it's a US or foreign IP | |
$IP = [IPAddress]$Response.query | |
$Location = "{0}, {1}" -f ($Response.city, $Response.country) | |
if ($Response.countryCode -eq 'US') { | |
$Location = "{0}, {1}" -f ($Response.city, $Response.region) | |
} | |
# Attempt to do a reverse DNS lookup. | |
# If it fails, the IP address will be used instead. | |
$HostName = $IP.ToString() | |
try { $HostName = [System.Net.Dns]::GetHostEntry($IP).HostName } | |
catch { } | |
# Construct an object to return to the pipeline | |
[PSCustomObject]@{ | |
PSComputerName = $Response.PSComputerName | |
IPAddress = $IP | |
HostName = $HostName | |
Location = $Location | |
ISP = $Response.isp | |
Organization = $Response.org | |
} | |
} | |
else { | |
Write-Error "Error getting IP info." | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment