有点像perl中的<statement> || die
,我可以将它与每个关键语句放在一起,以避免在出现问题时用脚本的其余部分打扰powershell。
大多数命令都支持-ErrorAction
公共参数。指定-ErrorAction Stop
通常会在出现错误时停止脚本。参见Get-Help about_CommonParameters
。
默认情况下,-ErrorAction
为Continue
。您可以通过更改$ErrorActionPreference
的值来更改默认选项。参见Get-Help about_Preference_Variables
。
如果冗长确实是一个问题,那么-ErrorAction
将别名为-ea
。
在PowerShell中实现类似...|| die
的构造而不需要添加巨大的try-catch构造的另一种方法是使用自动变量$?
来自Get-Help about_Automatic_variables
:
$?
Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.
只需在每个关键语句后添加以下内容:
if(-not $?){
# Call Write-EventLog or write $Error[0] to an xml or txt file if you like
Exit(1)
}