Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Get-Geolocation {
- param( [IPAddress]$IPv4="", [Int]$MaxCacheAge=172800, [String]$CacheLocation=".\" )
- # Ensure we have write access to default cache location or move to homedir
- Try {
- [IO.File]::OpenWrite("$CacheLocation.geocache").close()
- } Catch {
- $CacheLocation = "~\"
- }
- # Ensure cache file exists
- if ( !(Test-Path "$CacheLocation.geocache" -PathType Leaf) ) {
- @().GetEnumerator() | ConvertTo-Json | Out-File "$CacheLocation.geocache";
- }
- # Load cache
- $GeoCache = @(Get-Content "$CacheLocation.geocache" | ConvertFrom-Json);
- # De-nest the loaded cache because powershell is weird
- If ( $GeoCache[0] -AND $GeoCache[0].GetType() -eq [System.Object[]] ) { $GeoCache = $GeoCache[0] }
- #if ( $GeoCache[0].GetType -ne [String] ) { $GeoCache = $GeoCache[0] }
- # Search for address
- foreach ($CacheEntry in $GeoCache) {
- if ($CacheEntry.IPv4 -eq [String]$IPv4 -AND $MaxCacheAge -ne 0) { # 0 effectively means "skip cache entries"
- # Calculate entry age in seconds
- $Age = ( New-TimeSpan -Start ([DateTime]($CacheEntry.Timestamp)) -End (Get-Date) ).TotalSeconds;
- if ($Age -lt $MaxCacheAge) {
- # Short circuit on cache hit
- return $CacheEntry;
- }
- }
- }
- # Look up address not found in cache
- try {
- $request = Invoke-RestMethod -Method Get -Uri "https://ipinfo.io/$IPv4/geo"
- $location = [PSCustomObject]@{
- IPv4 = [String]$IPv4
- City = $request.city
- Region = $request.region
- Country = $request.country
- Timestamp = [String](Get-Date)
- }
- } catch {
- $location = $false
- }
- # Add location to cache
- $GeoCache += $location
- # Save cache
- $GeoCache.GetEnumerator() | ConvertTo-Json | Out-File "$CacheLocation.geocache" -Encoding ascii;
- Return $location;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement