Advertisement
Nestor10

Get-Geolocation

Mar 14th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Get-Geolocation {
  2.     param( [IPAddress]$IPv4="", [Int]$MaxCacheAge=172800, [String]$CacheLocation=".\" )
  3.     # Ensure we have write access to default cache location or move to homedir
  4.     Try {
  5.         [IO.File]::OpenWrite("$CacheLocation.geocache").close()
  6.     } Catch {
  7.         $CacheLocation = "~\"
  8.     }
  9.  
  10.     # Ensure cache file exists
  11.     if ( !(Test-Path "$CacheLocation.geocache" -PathType Leaf) ) {
  12.         @().GetEnumerator() | ConvertTo-Json | Out-File "$CacheLocation.geocache";
  13.     }
  14.    
  15.     # Load cache
  16.     $GeoCache = @(Get-Content "$CacheLocation.geocache" | ConvertFrom-Json);
  17.    
  18.     # De-nest the loaded cache because powershell is weird
  19.     If ( $GeoCache[0] -AND $GeoCache[0].GetType() -eq [System.Object[]] ) { $GeoCache = $GeoCache[0] }
  20.        
  21.     #if ( $GeoCache[0].GetType -ne [String] ) { $GeoCache = $GeoCache[0] }
  22.  
  23.     # Search for address
  24.     foreach ($CacheEntry in $GeoCache) {
  25.         if ($CacheEntry.IPv4 -eq [String]$IPv4 -AND $MaxCacheAge -ne 0) { # 0 effectively means "skip cache entries"
  26.             # Calculate entry age in seconds
  27.             $Age = ( New-TimeSpan -Start ([DateTime]($CacheEntry.Timestamp)) -End (Get-Date) ).TotalSeconds;
  28.             if ($Age -lt $MaxCacheAge) {
  29.                 # Short circuit on cache hit
  30.                 return $CacheEntry;
  31.             }
  32.         }
  33.     }
  34.  
  35.     # Look up address not found in cache
  36.     try {
  37.         $request = Invoke-RestMethod -Method Get -Uri "https://ipinfo.io/$IPv4/geo"
  38.  
  39.         $location = [PSCustomObject]@{
  40.             IPv4 = [String]$IPv4
  41.             City = $request.city
  42.             Region = $request.region
  43.             Country = $request.country
  44.             Timestamp = [String](Get-Date)
  45.         }
  46.     } catch {
  47.         $location = $false
  48.     }
  49.  
  50.     # Add location to cache
  51.     $GeoCache += $location
  52.    
  53.     # Save cache
  54.     $GeoCache.GetEnumerator() | ConvertTo-Json | Out-File "$CacheLocation.geocache" -Encoding ascii;
  55.  
  56.     Return $location;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement