2014-10-13 70 views
1

問題:PowerShell腳本停止,因爲這應該由try塊使用$ ErrorActionPreference時被捕獲的異常的

例子:

$ErrorActionPreference = 'Stop' 
try { 
    ThisCommandWillThrowAnException 
} catch { 
    Write-Error 'Caught an Exception' 
} 
# this line is not executed. 
Write-Output 'Continuing execution' 

回答

2

解決方案:Write-Error實際上默認會拋出非終止異常。當$ErrorActionPreference = 'Stop'被設置時,Write-Error在catch塊中拋出一個終止異常。

覆蓋此使用-ErrorAction 'Continue'

$ErrorActionPreference = 'Stop' 
try { 
    ThisCommandWillThrowAnException 
} catch { 
    Write-Error 'Caught an Exception' -ErrorAction 'Continue' 
} 
# this line is now executed as expected 
Write-Output 'Continuing execution' 
+0

也可參閱http://stackoverflow.com/questions/9294949/when-should-i-use-write-error-vs-throw安迪·阿里斯門迪的回答 – Vlad