2014-10-13 68 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