PowerShell: Try...Catch...Finally 实现方法
代码如下:
function Try { param ( [ScriptBlock]$Command = $(throw "The parameter -Command is required."), [ScriptBlock]$Catch = { throw $_ }, [ScriptBlock]$Finally = {} ) & { $local:ErrorActionPreference = "SilentlyContinue" trap { trap { & { trap { throw $_ } &$Finally } throw $_ } $_ | & { &$Catch } } &$Command } & { trap { throw $_ } &$Finally } }
使用示例:
代码如下:
# Example usage Try { echo " ::Do some work..." echo " ::Try divide by zero: $(0/0)" } -Catch { echo " ::Cannot handle the error (will rethrow): $_" #throw $_ } -Finally { echo " ::Cleanup resources..." }
相关推荐
highwaymanhw 2020-09-06
哥哥的CSDN集 2020-05-06
sufwei 2014-02-21
Huangguohao 2019-06-13
一万年太久 2018-05-14
邓博学习笔记 2016-04-20
zls 2011-09-03
DrYangZDY 2007-11-24