PowerShell: Try...Catch...Finally 实现方法
程序员文章站
2022-04-09 14:52:55
复制代码 代码如下:function try { p...
复制代码 代码如下:
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..."
}
下一篇: ruby 对象的初始化 方法