我想运行一个外部进程,并将其命令输出捕获到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"
这样的事情应该起作用
$OutputVariable = Get-Process
$OutputVariable | Out-File -FilePath "D:\Program Files\tool\var\global\reports\20191122_174015_hostname"
如果尝试从字符串中提取变化的路径,则将需要采用某种方法来仅识别该特定路径。在这种情况下,可以使用-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。实际上,您可能需要对此进行调整。