Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在windows power shell中将输出存储为单独的变量?_Windows_Powershell_Cmd_Powershell 2.0_Powershell 3.0 - Fatal编程技术网

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

如何在windows power shell中将输出存储为单独的变量?,windows,powershell,cmd,powershell-2.0,powershell-3.0,Windows,Powershell,Cmd,Powershell 2.0,Powershell 3.0,我希望根据用户的IP地址获取其地理位置,然后在脚本中进一步使用这些值。我正在使用这个命令 $pos=(Invoke-RestMethod http://ipinfo.io/loc) 此命令返回用逗号(,)分隔的纬度和经度值。如下图所示 -20.003,110.009809 如何分别访问/索引它们并将其存储为单独的变量?例如,如果我使用$pos[1],它不会返回经度值 还请建议是否有更好的方法在windows cmd中执行此操作,而不是在power shell中执行此操作。您可以从批处理文件调

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

$pos=(Invoke-RestMethod http://ipinfo.io/loc)
此命令返回用逗号(,)分隔的纬度和经度值。如下图所示

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

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

您可以从批处理文件调用:

@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%
  • 如果无法确定系统上是否存在此问题,请在powershell.exe之后添加
    -ExecutionPolicy Bypass

  • 如果要使用powershell核心而不是Windows powershell,请使用
    pwsh.exe
    而不是
    powershell.exe


至于:

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

针对如何单独访问/索引它们并作为单独变量存储的问题,
我会考虑不先分开它们,但是使用它可以保持纬度/经度的组合,但可以单独访问:

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

对于
Invoke RestMethod
,没有本机Cmd选项,因此您需要使用第三方工具,如
curl
。在cmd中解析字符串非常痛苦,为什么不坚持使用Powershell呢?唯一的原因是power shell脚本需要提升权限,并通过向脚本中添加“\”来请求用户运行脚本,或者通过执行命令(set executionpolicy remotesigned)来抑制此警告,这对于新手用户来说非常可怕。
Add-type -AssemblyName System.Device
$Geo = New-Object System.Device.Location.GeoCoordinate($Pos.Split(','))
$Geo.Latitude
-20.003