2015-09-02 113 views

回答

10

通常你會使用$?檢查的最後一條語句的執行狀態:

PS C:\> Write-Output 123 | Out-Null; $? 
True 
PS C:\> Non-ExistingCmdlet 123 | Out-Null; $? 
False 

但是,這不會與Invoke-Expression工作,因爲即使傳遞給Invoke-Expression表達內聲明可能會失敗,在Invoke-Expression調用它自會成功(即表達,雖然無效/非功能被調用沒有少)


隨着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 
} 

而是依靠沒有任何流水線輸出

+0

這一個很好 –

+0

最後一個例子的第二行必須是'$ Expr + ='; $?''以避免直接解釋'$?'。 – letmaik

+0

@letmaik很好地發現,完全忽略了 –

6

在PowerShell中可以通過檢查automatic variables

$? 
    Contains True if last operation succeeded and False otherwise. 

和/或

$LASTEXITCODE 
    Contains the exit code of the last Win32 executable execution. 

前者用於PowerShell命令,後者爲外部命令(如%errorlevel%在評估執行狀態批處理腳本)。

這對你有幫助嗎?

+1

無論如何'Invoke-Expression'總是將'$?'設置爲'$ true',所以'$?'在這種情況下不會起作用。 – ForNeVeR

+0

$ LASTEXITCODE的作品。謝謝! – Nicholas

相關問題