Skip to content

Instantly share code, notes, and snippets.

@mvanantw
Created January 18, 2019 14:32
Show Gist options
  • Save mvanantw/d8f6093221b3a18449dbd7d6331819b1 to your computer and use it in GitHub Desktop.
Save mvanantw/d8f6093221b3a18449dbd7d6331819b1 to your computer and use it in GitHub Desktop.
PowerShell function to get the geolocation for one or more IP Addresses
function Get-MvaIpLocation {
<#
.SYNOPSIS
Retrieves Geo IP location data
.DESCRIPTION
This command retrieves the Geo IP Location data for one or more IP addresses
.PARAMETER IPAddress <String[]>
Specifies one or more IP Addresses for which you want to retrieve data for.
.EXAMPLE
Get-MvaIpLocation -ipaddress '124.26.123.240','123.25.96.8'
.EXAMPLE
'124.26.123.240','123.25.96.8' | Get-MvaIpLocation
.LINK
https://get-note.net/2019/01/18/use-powershell-to-find-ip-geolocation
.INPUTS
System.String
.OUTPUTS
System.Management.Automation.PSCustomObject
.NOTES
Author: Mario van Antwerpen
Website: https://get-note.net
#>
[cmdletbinding()]
[OutputType([System.Management.Automation.PSCustomObject])]
Param (
[Parameter(ValueFromPipeline, Mandatory, Position = 0, HelpMessage = "Enter an IP Address")]
[ValidateScript({
if ($_ -match '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$') {
$true
} else {
Throw "$_ is not a valid IPv4 Address!"
}
})]
[string[]]$ipaddress
)
begin {
Write-Verbose -message "Starting $($MyInvocation.Mycommand)"
}
process {
foreach ($entry in $ipaddress) {
$restUrl = "http://ip-api.com/json/$entry"
try {
Write-Verbose -Message "Connecting to rest endpoint"
$result = Invoke-RestMethod -Method get -Uri $restUrl
Write-output $result
}
catch {
Write-Verbose -Message "Catched and error"
$PSCmdlet.ThrowTerminatingError($PSitem)
}
}
}
end {
Write-Verbose -message "Ending $($MyInvocation.Mycommand)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment