问题描述
我想按照以下规则重定向PowerShell中命令的输出:
I would like to redirect the output of a command in PowerShell, following these rules:
-
命令存储到变量
The command is stored to a variable
输出必须实时写入控制台(即 ping结果),包括错误
Output must be written to the console in real-time (i.e. "ping" results), including errors
输出必须存储到一个变量中,包括错误(在此处不是实时的)
Output must be stored to a variable, including errors (real-time is not mandatory here)
这是我的测试,假设:
$command = "echo:"
测试错误重定向,并且:
to test errors redirection, and:
$command = "ping 127.0.0.1"
测试实时输出。
-
输出是实时编写的,错误根本不会重定向
Output is written in real-time, errors are not redirected at all
Invoke-Expression $command 2>&1 | Tee-Object -Variable out_content
输出是实时编写的,错误仅被重定向
Output is written in real-time, errors are only redirected to the console
Invoke-Expression ($command 2>&1) | Tee-Object -Variable out_content
Invoke-Expression $command | Tee-Object -Variable out_content 2>&1
输出不是用实时间,错误被正确地重定向到两个
Output is not written in real-time, errors are correctly redirected to both
(Invoke-Expression $command) 2>&1 | Tee-Object -Variable out_content
是否可能才能使这些规则协同工作?
Is it possible to get those rules working together?
推荐答案
一些一般性建议:
-
,因为它可能会带来安全风险并引入报价头痛;通常有更好,更安全的解决方案可用;除非没有其他解决方案,否则最好养成避免
Invoke-Expression
的习惯。
Invoke-Expression
should generally be avoided, because it can be a security risk and introduces quoting headaches; there are usually better and safer solutions available; best to form a habit of avoidingInvoke-Expression
, unless there is no other solution.
从来没有理由使用 Invoke-Expression
来简单地执行带有参数的外部程序,例如 ping 127.0.0.1
;只需直接调用 -支持这种直接调用是任何Shell的核心功能,PowerShell也不例外。
There is never a reason to use Invoke-Expression
to simply execute an external program with arguments, such as ping 127.0.0.1
; just invoke it directly - support for such direct invocations is a core feature of any shell, and PowerShell is no exception.
I 如果您确实需要将命令存储在变量中,或将其作为自变量 传递给以后,使用脚本块( {...}
);例如,使用 $ command = {ping 127.0.0.1}
代替 $ command ='ping 127.0.0.1'
,并使用&
,,或。
,。
针对您的问题的解决方法:
像以前一样无数次,在评论中提供了一种解决方案问题:
PetSerAl, as countless times before, has provided a solution in a comment on the question:
& { Invoke-Expression $command } 2>&1 | Tee-Object -Variable out_content
{...}
是一个脚本块文字,包含 Invoke-Expression
调用,并通过&
调用,即调用运算符,可将流重定向表达式 2>& 1
应用于&
{ ... }
is a script-block literal that contains the Invoke-Expression
call, and it is invoked with &
, the call operator, which enables applying stream-redirection expression 2>&1
to the &
call, which bypasses the bug.
这篇关于将Powershell输出和错误重定向到控制台(实时)和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!