PowerShell: Try...Catch...Finally 实现方法_PowerShell教程-查字典教程网
PowerShell: Try...Catch...Finally 实现方法
PowerShell: Try...Catch...Finally 实现方法
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:functionTry{param([ScriptBlock]$Command=$(throw"Theparameter-...

复制代码 代码如下:

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..."

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新PowerShell学习
    热门PowerShell学习
    脚本专栏子分类