Skip to content

Instantly share code, notes, and snippets.

@markwragg
Last active May 30, 2017 08:40
Show Gist options
  • Save markwragg/0cbe5094c47bb0489636f421fc793e54 to your computer and use it in GitHub Desktop.
Save markwragg/0cbe5094c47bb0489636f421fc793e54 to your computer and use it in GitHub Desktop.
PowerShell function that uses Google APIs to get the current local time for any valid address string. Requires a Google API key.
Function Get-LocalTime {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
$Address,
$Time = (Get-Date),
#Get an API key from here: https://developers.google.com/apis-explorer/
$APIKey = (Import-Clixml "$env:USERPROFILE\$ENV:USERNAME-GoogleApi.xml"),
$Timeout = 5
)
Function Get-UnixTime {
Write-Output ( New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date $Time) ).TotalSeconds
}
Try {
$Results = Invoke-RestMethod "https://maps.googleapis.com/maps/api/geocode/json?address=$Address&key=$APIKey" -TimeoutSec $Timeout
$Location = $Results.results.geometry.location
$Coordinates = "$($Location.lat),$($Location.lng)"
$APIResult = Invoke-RestMethod "https://maps.googleapis.com/maps/api/timezone/json?location=$Coordinates&timestamp=$(Get-UnixTime)&key=$APIKey" -TimeoutSec $Timeout
Write-Output @{
Address = $Results.results.formatted_address;
DateTime = ( (Get-Date $Time).ToUniversalTime() ).AddSeconds($APIResult.rawOffset).AddSeconds($APIResult.dstOffSet);
}
} Catch {
Write-Error "Failed to get time for $Address due to error: $_"
Return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment