If you ever find yourself in a situation where you don’t really know where you are, I got you covered!

This small function will try to get the longitude/latitude coordinates and use the OpenStreetMap API to perform a reverse lookup to get address information for your current location.

function Get-GeoLocation {
Get current location.
This function tries to get the latitude and longitude coordinates of the current location,
and will look up those coordinates on OpenStreetMap to get address information.
Will try to get address information about your current location.
Get-GeoLocation -LatLon
Will return the Latitude and Longitude of your current location.
Author: Øyvind Kallstad
Version: 1.0
Date: 09.08.2016
param (
# Number of times the function tries to get the coordinates. Default value is 4.
[int] $NumTries = 4,
# Number of milliseconds to sleep between each try. Default value is 1000.
[int] $SleepBetweenTries = 1000,
# Use this switch to indicate that you want the Latitude and Longitude returned.
# Address lookup will not be performed.
[switch] $LatLon
try {
Add-Type AssemblyName 'System.Device'
catch {
Write-Warning 'Unable to load the needed assembly (System.Device).'
$watcher = New-Object TypeName System.Device.Location.GeoCoordinateWatcher ArgumentList 'High'
[void]$watcher.TryStart($true, [TimeSpan]::FromMilliseconds(1000))
$count = 0
do {
Start-Sleep Milliseconds $SleepBetweenTries
} while (($watcher.Position.Location.IsUnknown) -or ($count -ge $numTries))
if ($watcher.Position.Location.IsUnknown) {
Write-Warning 'Couldn''t get coordinates.'
else {
$coord = $watcher.Position.Location
if (-not ($LatLon)) {
$url = "$($coord.Latitude.ToString().Replace(',','.'))&lon=$($coord.Longitude.ToString().Replace(',','.'))&zoom=18&addressdetails=1"
try {
$result = Invoke-RestMethod Uri $url
Write-Output ($result.address)
catch {
Write-Warning $_.Exception.Message
else {
Write-Output ([PSCustomObject][Ordered] @{
Latitude = $coord.Latitude
Longitude = $coord.Longitude
New-Alias Name whereami Value Get-GeoLocation Force

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s