[英]Replace 2>&1 in the PowerShell script
We use the below function in one of our PowerShell scripts.我们在我们的 PowerShell 脚本之一中使用以下函数。 Can someone explain what "2>&1" means here?有人可以解释这里的“2>&1”是什么意思吗? Is there any equivalent full cmdlet to replace this value?是否有任何等效的完整 cmdlet 来替换此值?
function InvExp {
param (
[string]$cmd
)
$er = (invoke-expression $cmd) 2>&1
if($er.Exception){
throw $er.Exception
}
}
As Santiago Squarzon notes, 2>&1
is a redirection ( >
) that redirects output stream number 2
(the error stream) into ( &
) stream number 1
(the success stream) .正如Santiago Squarzon 所指出的, 2>&1
是一个重定向( >
),它将输出流编号2
(错误流)重定向到 ( &
) 流编号1
(成功流) 。
2
in redirections refers to such a program's stderr output, and 1
(the default stream) to its stdout output.调用外部程序时,重定向中的2
指的是此类程序的标准错误输出,而1
(默认流)指的是其标准输出输出。What your function in effect does is to promote any error - irrespective of whether it is a non -terminating or a (statement-) terminating error - to a fatal error ( script -terminating aka runspace-terminating error).您的功能实际上是将任何错误(无论它是非终止错误还是(语句)终止错误)提升为致命错误(脚本终止又名运行空间终止错误)。
However, I propose a simpler implementation , which also avoids the use of Invoke-Expression
, which is generally to be avoided , by instead requiring that a script block ( { ... }
) rather than a string be passed as an argument:但是,我提出了一个更简单的实现,它也避免了使用Invoke-Expression
,这通常是应该避免的,而是要求一个脚本块( { ... }
)而不是一个字符串作为参数传递:
function Assert-NoError {
param(
[scriptblock] $cmd
)
$ErrorActionPreference = 'Stop'
. $cmd
}
You would then invoke the function as follows, for example:然后,您将按如下方式调用该函数,例如:
Assert-NoError { Get-Process test }
Note:笔记:
$ErrorActionPreference = 'Stop'
creates a local instance of the the $ErrorActionPreference
preference variable , and by setting it to Stop
ensures that any error results in a fatal error by default. $ErrorActionPreference = 'Stop'
创建$ErrorActionPreference
首选项变量的本地实例,并通过将其设置为Stop
确保默认情况下任何错误都会导致致命错误。
The above implementation has the added advantage that any success output that precedes an error is output before execution is aborted.上述实现还有一个额外的好处,即任何在错误之前的成功输出都会在执行被中止之前输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.