2012-03-30 37 views

回答

182

$ErrorActionPreference = "Stop"會讓你成爲那裏的一部分(即這對於cmdlet來說很好)。

但是對於EXE,您需要在每次exe調用後自行檢查$LastExitCode並確定是否失敗。不幸的是,我不認爲PowerShell在這裏可以提供幫助,因爲在Windows上,EXE在構成「成功」或「失敗」退出代碼的構成方面並不十分一致。大多數遵循0表示成功的UNIX標準,但並非全部都是。檢查出CheckLastExitCode function in this blog post。你可能會覺得它很有用。

+2

'$ ErrorActionPreference =「Stop」'適用於行爲良好的程序(成功時返回0)? – 2012-03-30 20:56:52

+10

不,它根本不適用於EXE。它僅適用於正在運行的PowerShell cmdlet。這是一種痛苦,但你必須在每次EXE調用後檢查$ LastExitCode,檢查是否與預期的退出代碼相對應,如果該測試表明失敗,則必須拋出以終止腳本的執行,例如'throw「$ exe失敗,並退出代碼$ LastExitCode」',其中$ exe只是EXE的路徑。 – 2012-03-30 21:18:43

+2

接受,因爲它包含如何使它與外部程序一起使用的信息。 – 2012-04-22 22:23:21

51

您應該可以通過在腳本開始時使用語句$ErrorActionPreference = "Stop"來完成此操作。

默認設置$ErrorActionPreferenceContinue,這就是爲什麼你看到你的腳本在發生錯誤後繼續前進的原因。

+12

這不會影響程序,只會影響cmdlet。 – Joey 2012-03-30 19:23:49

4

不幸的是,due to buggy cmdlets like New-RegKey and Clear-Disk,這些答案都不夠。目前我已經在任何PowerShell腳本的頂部定位了以下幾行來維護我的理智。

Set-StrictMode -Version Latest 
$ErrorActionPreference = "Stop" 
$PSDefaultParameterValues['*:ErrorAction']='Stop' 

,然後任何本地調用得到這個待遇:

native_call.exe 
$native_call_success = $? 
if (-not $native_call_success) 
{ 
    throw 'error making native call' 
} 

即本地通話模式正在慢慢成爲通用夠我,我也許應該考慮選項,使其更加簡潔。我仍然是一個powershell新手,所以建議是值得歡迎的。

1

我來到這裏尋找同樣的事情。 $ ErrorActionPreference =「Stop」立即殺死我的shell,當我想在終止之前看到錯誤消息(暫停)。在我的批處理情感回落:

IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF 

我發現,這個工程幾乎爲我特別PS1腳本相同:

Import-PSSession $Session 
If ($? -ne "True") {Pause; Exit} 
0

你需要稍微不同的錯誤處理的PowerShell函數和調用的exe,您需要確保告訴腳本的調用者它已失敗。從Psake庫中構建Exec之上,具有以下結構的腳本將停止所有錯誤,並且可用作大多數腳本的基本模板。

Set-StrictMode -Version latest 
$ErrorActionPreference = "Stop" 


# Taken from psake https://github.com/psake/psake 
<# 
.SYNOPSIS 
    This is a helper function that runs a scriptblock and checks the PS variable $lastexitcode 
    to see if an error occcured. If an error is detected then an exception is thrown. 
    This function allows you to run command-line programs without having to 
    explicitly check the $lastexitcode variable. 
.EXAMPLE 
    exec { svn info $repository_trunk } "Error executing SVN. Please verify SVN command-line client is installed" 
#> 
function Exec 
{ 
    [CmdletBinding()] 
    param(
     [Parameter(Position=0,Mandatory=1)][scriptblock]$cmd, 
     [Parameter(Position=1,Mandatory=0)][string]$errorMessage = ("Error executing command {0}" -f $cmd) 
    ) 
    & $cmd 
    if ($lastexitcode -ne 0) { 
     throw ("Exec: " + $errorMessage) 
    } 
} 

Try { 

    # Put all your stuff inside here! 

    # powershell functions called as normal and try..catch reports errors 
    New-Object System.Net.WebClient 

    # call exe's and check their exit code using Exec 
    Exec { setup.exe } 

} Catch { 
    # tell the caller it has all gone wrong 
    $host.SetShouldExit(-1) 
    throw 
}