powershell从变量中提取字符串以分配另一个变量

问题描述 投票:-1回答:2

我想运行一个外部进程,并将其命令输出捕获到PowerShell中的变量中。我目前正在使用此:我将捕获"D:\Program Files\tool\var\global\reports\20191122_174015_hostname",然后分配给另一个变量。

$OutputVariable = (command) | Out-String

$$ OutputVariable:

Gathering system informations
  Discovered server
  failed to 1 of 5 server, for details see: C:\TEST
failed.log
  Output for HOSTNAME at: C:\OUTPUT_11222019
Gather DONE
Execution time: 32 secs
To create a report for server, run one of the following:
  capacity   : test.exe --report --capacity "D:\Program Files\tool\var\global\reports\20191122_174015_hostname"
  traditional: test.exe --report --traditional "D:\Program Files\tool\var\global\reports\20191122_174015_hostname"
regex powershell
2个回答
0
投票

这样的事情应该起作用

$OutputVariable = Get-Process
$OutputVariable | Out-File -FilePath "D:\Program Files\tool\var\global\reports\20191122_174015_hostname"

0
投票

如果尝试从字符串中提取变化的路径,则将需要采用某种方法来仅识别该特定路径。在这种情况下,可以使用-match创建正则表达式匹配条件。

$null = $OutputVariable -match 'capacity.*?"([^"]+)"'
$Matches[1]

或者,也可以使用.NET Regex类中的Match方法。

[regex]::Match($outputvariable,'capacity.*?"([^"]+)"').Groups[1].Value

说明:

  • [capacity从字面上匹配容量
  • .*?匹配尽可能少的字符。这基本上使我们到达了容量后的第一个"字符。
  • ["从字面上匹配"
  • ([^"]+)[^"]匹配不等于"的所有内容,并且匹配一次或多次(+)。 ()创建一个捕获组,我们以后可以参考。捕获组名为1

成功匹配将导致两个条目存储在自动变量$Matches中。索引0是整个匹配字符串,索引1是第一个捕获组。由于您只想查看路径,因此我们仅从索引1检索数据。$Matches 如果不存在匹配项,则不会更新。因此它可以保留以前的匹配值。

[$null用于抑制-match运算符的输出。

注:这假定路径在某些点之前由双引号引起来,并带有单词capacity。实际上,您可能需要对此进行调整。

© www.soinside.com 2019 - 2024. All rights reserved.