您的位置:首页 > 运维架构 > Shell

PowerShell: Try...Catch...Finally 实现方法

2012-06-22 08:47 316 查看
PowerShell 本身有很多很好的错误控制,但是习惯于.net编程的人员,更喜欢用Try Catch Finally方法,尤其当有一段代码必须被执行到的时候。现在好了,adweigert 想出了一个好方法来实现。这个函数已经在多种情况下测试过,希望能对你有帮助。

1 function Try
2 {
3 param
4 (
5 [ScriptBlock]$Command = $(throw "The parameter -Command is required."),
6 [ScriptBlock]$Catch = { throw $_ },
7 [ScriptBlock]$Finally = {}
8 )
9
& {
$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..."
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐