如何获得“调用表达式"的状态,成功还是失败? [英] How to get status of "Invoke-Expression", successful or failed?
问题描述
Invoke-Expression
将返回被调用命令的所有文本.
Invoke-Expression
will return all the text of the command being invoked.
但是我怎样才能得到这个命令是成功执行还是失败的系统返回值呢?在 CMD 中,我可以使用 %errorlevel%
来获取外部命令执行状态.PowerShell 怎么样?
But how can I get the system return value of whether this command has been executed successfully or with a failure? In CMD I could use %errorlevel%
to get external command execution state. What about PowerShell?
推荐答案
通常你会使用 $?
来检查最后执行的语句的状态:
Normally you would use $?
to inspect the status of the last statement executed:
PS C:\> Write-Output 123 | Out-Null; $?
True
PS C:\> Non-ExistingCmdlet 123 | Out-Null; $?
False
但是,这不适用于 Invoke-Expression
,因为即使传递给 Invoke-Expression
的表达式中的语句可能会失败,Invoke-Expression
调用它自己会成功(即表达式,尽管无效/非功能性被调用)
However, this won't work with Invoke-Expression
, because even though a statement inside the expression passed to Invoke-Expression
may fail, the Invoke-Expression
call it self will have succeeded (ie. the expression, although invalid/non-functional was invoked none the less)
使用 Invoke-Expression
你必须使用 try:
With Invoke-Expression
you'll have to use try:
try {
Invoke-Expression "Do-ErrorProneAction -Parameter $argument"
} catch {
# error handling go here, $_ contains the error record
}
或陷阱:
trap {
# error handling goes here, $_ contains the error record
}
Invoke-Expression "More-ErrorProneActions"
<小时>
另一种方法是将 ";$?"
附加到要调用的表达式中:
The alternative is the append ";$?"
to the expression you want to invoke:
$Expr = "Write-Host $SomeValue"
$Expr += ';$?'
$Success = Invoke-Expression $Expr
if(-not $Success){
# seems to have failed
}
但依赖于没有任何管道输出
but relies on there not being any pipeline output
这篇关于如何获得“调用表达式"的状态,成功还是失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!