Use PowerShell to find IP Geolocation

In log files from web servers you often find strange requests. For example requests for wp-login.php on server that don’t have PHP or WordPress installed. Or that someone is requesting the same page over and over. Most of the times this is not a real problem. But it gets a problem or at least annoying when you get hundreds or thousands of these requests from the same IP address.

If I see things like that happening the first step is to find out where the request is coming from. For that I would go the certain websites. Based on the outcome I would then block that IP address or even the whole subnet in the firewall. Problem is that some of these website only allow a limit amount of lookups.

To make it more easier for myself I created a PowerShell function that uses a Rest API to do the lookup.

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)"
}
}

The function is easy to use. It has one parameter -IPAddress that can contain one more IP Addresses. It also accepts pipeline input.

One thought on “Use PowerShell to find IP Geolocation

Comments are closed.