Invoke-Expression将返回正在调用的命令的所有文本。
但是,如何获得该命令是否已成功执行或失败的系统返回值?在CMD中,我可以使用%errorlevel%获取外部命令执行状态。那PowerShell呢?
发布于 2015-09-02 09:09:08
通常,您将使用$?来检查执行的最后一条语句的状态:
PS C:\> Write-Output 123 | Out-Null; $?
True
PS C:\> Non-ExistingCmdlet 123 | Out-Null; $?
False但是,这不适用于Invoke-Expression,因为即使传递给Invoke-Expression的表达式中的语句可能失败,Invoke-Expression调用它的self也会成功(即。尽管调用了无效/非功能性表达式,但还是调用了该表达式)
对于Invoke-Expression,您必须使用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"另一种方法是将";$?"追加到要调用的表达式:
$Expr = "Write-Host $SomeValue"
$Expr += ';$?'
$Success = Invoke-Expression $Expr
if(-not $Success){
# seems to have failed
}但依赖于没有任何管道输出
发布于 2019-03-06 22:30:34
如果Invoke-Expression调用的可执行文件支持它,则可以使用$LASTEXITCODE。但是,您必须注意变量范围的确定。
function foo
{
$global:LASTEXITCODE = 0 # Note the global prefix.
Invoke-Expression "dotnet build xyz" # xyz is meaningless, to force nonzero exit code.
Write-Host $LASTEXITCODE
}
foo如果运行它,输出将是:
Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.
MSBUILD : error MSB1009: Project file does not exist.
Switch: xyz
1观察结尾处的1表示非零退出代码。
如果您忘记了global:前缀,那么输出将有0。我相信这是因为您对LASTEXITCODE的函数范围定义将隐藏全局设置的定义。
发布于 2015-09-02 09:02:38
在PowerShell中,您可以通过检查自动变量来评估执行状态
$?
Contains True if last operation succeeded and False otherwise.和/或
$LASTEXITCODE
Contains the exit code of the last Win32 executable execution.前者用于PowerShell cmdlet,后者用于外部命令(如批处理脚本中的%errorlevel% )。
这对你有帮助吗?
https://stackoverflow.com/questions/32348794
复制相似问题