我正在尝试存储来自 Invoke-expression
的输出到一个变量以及在屏幕上。我有 PS 日志记录,它会自动将所有内容记录为 Write-Host
在一个文件中。现在我正在使用 Invoke-Expression
这似乎要么在屏幕上打印输出,要么打印到变量,我需要两者
我所尝试的是:
$var = "C:\ER\work\Canny.exe -Init ER\ER2 Get-ip"
$val = Invoke-Expression $var
这不会在屏幕上打印任何内容,因此我无法知道运行时是否有任何问题。我后来做了一个
Write-Host
的 $val
它记录了它,但有时知道发生了什么为时已晚如果我使用:
Invoke-Expression $var
什么都没有记录(显然),但是有控制台输出,如果我想在一段时间后查看日志发生了什么,我无法进行调查。
我也试过:
Invoke-Expression $var -OutVariable out
或者
Invoke-Expression $var -OutVariable $out
这在这里没有用。我还创建了一个脚本块并尝试使用
Invoke-Command
但同样没用,我只需要它在屏幕和变量上打印输出。
最佳答案
Invoke-Expression -Command $var -OutVariable out
应该可以工作(变量 + 控制台输出),但是发生了一些奇怪的事情。它适用于 ISE,但在普通的 PowerShell 控制台中,我得到一个空的 ArrayList
.如果您将其通过管道传输到另一个命令,例如 Out-String
它有效(但这将返回一个多行字符串)。
Invoke-Expression -Command $var | Out-String -OutVariable out
要么我忘记了某些东西,要么可能是
Invoke-Expression
的错误.一种解决方法是使用
Tee-Object
其行为与 -OutVariable
相同.The Tee-Object cmdlet redirects output, that is, it sends the output of a command in two directions (like the letter "T"). It stores the output in a file or variable and also sends it down the pipeline. If Tee-Object is the last command in the pipeline, the command output is displayed at the prompt.
例子:
Invoke-Expression $var -OutVariable | Tee-Object -Variable out
或(到文件):
Invoke-Expression $var -OutVariable | Tee-Object -FilePath c:\text.txt
请注意,它会覆盖
$out
中的内容.
关于powershell - 在屏幕和变量中调用表达式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330115/