1

I want to get geolocation of a user based on its IP address and then later using these values further along with the script. I am using this command.

$pos=(Invoke-RestMethod http://ipinfo.io/loc)

This command returns me latitude and longitude value separated by a comma (,). as shown below.

-20.003,110.009809

How can I access/index them separately and store as a separate variable? For example, If I use $pos[1], it does not return me longitude value.

Please also suggest if there is some better way of doing it in windows cmd rather than power shell.

Sahar
  • 23
  • 6
  • 1
    There is no native Cmd alternative for `Invoke-RestMethod`, so you need to use 3rd party tools such as `curl`. Parsing strings in cmd is quite painful, so why not stick with Powershell? – vonPryz Nov 20 '19 at 07:27
  • The only reason is power shell script requires elevated permissions and requests the user to run the script by adding ".\" to it or suppress this warning by executing a command (set-executionpolicy remotesigned) which is quite scary for a novice user. – Sahar Nov 20 '19 at 07:36

2 Answers2

1

You can call PowerShell's CLI from a batch file:

@echo off
setlocal

for /f "delims=, tokens=1,2" %%a in ('powershell.exe -noprofile -c Invoke-RestMethod http://ipinfo.io/loc') do set "lat=%%a" & set "long=%%b"

echo Latitude is %lat%, longitude is %long%
  • Add -ExecutionPolicy Bypass after powershell.exe if you can't be sure that script execution is enabled on your system.

  • Use pwsh.exe instead of powershell.exe if you want to use PowerShell Core instead of Windows PowerShell.


As for your PowerShell solution:

As a matter of habit, I suggest using PowerShell's -split operator rather than the [string] type's .Split() method, because the regular-expression-based -split offers more flexibility and features, as detailed in this answer:

$lat, $long = (Invoke-RestMethod http://ipinfo.io/loc) -split ','
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Specific to the question How can I access/index them separately and store as a separate variable?,
I would consider not separate them initially but use the GeoCoordinate Class which allows you keep the Latitude/Longitude combined but access separately:

Add-type -AssemblyName System.Device
$Geo = New-Object System.Device.Location.GeoCoordinate($Pos.Split(','))
$Geo.Latitude
-20.003
iRon
  • 20,463
  • 10
  • 53
  • 79