Here’s how you can determine the network geolocation of a Windows computer with a PowerShell script:
# Fetch Public IP-based Geolocation
function Get-Location {
$ipInfoUrl = "https://ipinfo.io/json"
try {
$response = Invoke-RestMethod -Uri $ipInfoUrl
Write-Output "IP: $($response.ip)"
Write-Output "City: $($response.city)"
Write-Output "Region: $($response.region)"
Write-Output "Country: $($response.country)"
Write-Output "Location (Lat,Long): $($response.loc)"
Write-Output "ISP: $($response.org)"
Write-Output "Hostname: $($env:COMPUTERNAME)"
} catch {
Write-Output "Error fetching location: $_"
}
}
# Main Execution
Get-Location
The information can be utilized, for example, by sending the location via email when the computer starts and connects to the network, or for any purpose where knowing the location is desired.
Geolocation data source: https://ipinfo.io/
The script can be configured to perform the desired operations in the background without visible signs to the user, for example, when the machine starts, the user logs in, or at scheduled intervals.
Because the location is based on the IP address of the network connection, it is approximate. Additionally, VPN connections and internal routing within organizations can distort it significantly. Therefore, this method can be used in a limited way for applications where it can be expected to work reasonably well.
Happy scripting!