在屏幕和变量中调用表达式输出 [英] Invoke-expression output on Screen and in a variable
问题描述
我正在尝试将 Invoke-expression
的输出存储到一个变量以及屏幕上.我有 PS 日志记录,它自动将所有内容作为 Write-Host
记录在文件中.现在我正在使用 Invoke-Expression
似乎要么在屏幕上打印输出,要么打印到变量,我需要两者
I am trying to store output from Invoke-expression
into a variable as well as on screen. I have PS logging which automatically log everything as Write-Host
in a file. Now I am using Invoke-Expression
which seems to either print the output on Screen or to a variable, I need both
我所尝试的只是:
$var = "C:\ER\work\Canny.exe -Init ER\ER2 Get-ip"
$val = Invoke-Expression $var
这不会在屏幕上打印任何内容,因此我无法知道运行时是否有任何问题.我后来做了一个 $val
的 Write-Host
记录它,但有时知道发生了什么为时已晚如果我使用:
This doesn't print anything on Screen so I am unable to know if there are any issues while running. I later do a Write-Host
of $val
which logs it but its sometimes too late to know what happened
If I use:
Invoke-Expression $var
没有记录任何内容(显然),但有控制台输出,如果我想在一段时间后查看日志中发生了什么,我无法进行调查.我也试过:
Nothing is logged (obviously), but there is console output and if I want to see after sometime for logs what happened, I have no way of Investigating. I have also tried :
Invoke-Expression $var -OutVariable out
或
Invoke-Expression $var -OutVariable $out
这在这里没有用.我还创建了一个脚本块并尝试使用
This is of no use here. I have also created a script block and tried with
Invoke-Command
但同样没用,我只需要它在屏幕和变量上打印输出.
but again of no use I just need it to print the output on Screen as well as to a variable.
推荐答案
Invoke-Expression -Command $var -OutVariable out
应该可以工作(变量 + 控制台输出),但是发生了一些奇怪的事情.它适用于 ISE,但在普通的 PowerShell 控制台中,我得到一个空的 ArrayList
.如果您将其通过管道传递给另一个命令,例如 Out-String
,它会起作用(但这将返回单个多行字符串).
Invoke-Expression -Command $var -OutVariable out
should work (variable + console output), but there's something weird going on. It works in ISE, but in a normal PowerShell console I get an empty ArrayList
. If you pipe it to another command like Out-String
it works (but this would return a single multi-line string).
Invoke-Expression -Command $var | Out-String -OutVariable out
要么是我忘记了什么,要么是 Invoke-Expression
的错误.
Either I'm forgetting something or it might be a bug with Invoke-Expression
.
一种解决方法是使用 Tee-Object
与 -OutVariable
的行为相同.
A workaround would be to use Tee-Object
which behaves the same as -OutVariable
.
Tee-Object cmdlet 重定向输出,即发送输出两个方向的命令(如字母T").它存储了在文件或变量中输出,并将其发送到管道中.如果Tee-Object 是管道中的最后一个命令,命令输出为显示在提示处.
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
中的内容.
Be aware that it overwrites the content in $out
.
这篇关于在屏幕和变量中调用表达式输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!