如何将输出存储为 windows 幂 shell 中的单独变量?

How to store output as a separate variables in windows power shell?

我想根据用户的 IP 地址获取用户的地理位置,然后在脚本中进一步使用这些值。我正在使用这个命令。

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

此命令return用逗号 (,) 分隔我的纬度和经度值。如下图

-20.003,110.009809

如何 access/index 将它们分开并存储为单独的变量?例如,如果我使用 $pos[1],它不会 return 我的经度值。

还请建议在 windows cmd 而不是电源 shell 中是否有更好的方法 shell。

您可以从批处理文件中调用 PowerShell's CLI

@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%
  • 如果您不能确定 script execution is enabled 在您的系统上,请在 powershell.exe 之后添加 -ExecutionPolicy Bypass

  • 如果您想使用 PowerShell Core 而不是 Windows PowerShell,请使用 pwsh.exe 而不是 powershell.exe


至于your PowerShell solution:

作为习惯,我建议使用 PowerShell 的 -split 运算符而不是 [string] 类型的 .Split() 方法,因为基于正则表达式的 -split 提供更多的灵活性和功能,详见 :

$lat, $long = (Invoke-RestMethod http://ipinfo.io/loc) -split ','

具体到问题我怎样才能access/index它们分开并存储为一个单独的变量?,
我会考虑 而不是 最初将它们分开,但使用 GeoCoordinate Class 允许您保持 Latitude/Longitude 组合但单独访问:

Add-type -AssemblyName System.Device
$Geo = New-Object System.Device.Location.GeoCoordinate($Pos.Split(','))
$Geo.Latitude
-20.003