【问题标题】:How to store output as a separate variables in windows power shell?如何在windows powershell中将输出存储为单独的变量?
【发布时间】:2020-03-15 20:01:48
【问题描述】:

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

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

此命令返回由逗号 (,) 分隔的纬度和经度值。如下图。

-20.003,110.009809

如何分别访问/索引它们并将它们存储为单独的变量?例如,如果我使用 $pos[1],它不会返回我的经度值。

还请建议是否有更好的方法在 windows cmd 中而不是在 power shell 中执行此操作。

【问题讨论】:

  • Invoke-RestMethod 没有原生 Cmd 替代方案,因此您需要使用 3rd 方工具,例如 curl。在cmd中解析字符串很痛苦,为什么不坚持使用Powershell呢?
  • 唯一的原因是 power shell 脚本需要提升权限并请求用户通过添加“.\”来运行脚本,或者通过执行命令 (set-executionpolicy remotesigned) 来禁止此警告,该命令是对于新手用户来说相当可怕。

标签: windows powershell cmd powershell-2.0 powershell-3.0


【解决方案1】:

您可以从批处理文件中调用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 提供了更多的灵活性和功能,详见 @987654324 @:

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

【讨论】:

    【解决方案2】:

    特定于问题我如何分别访问/索引它们并将它们存储为单独的变量?,
    我会考虑不最初将它们分开,但使用GeoCoordinate Class,它允许您保持纬度/经度组合但单独访问:

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

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 2019-10-27
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 2019-11-05
      • 1970-01-01
      相关资源
      最近更新 更多