PowerShell: Try...Catch...Finally 实现方法
程序员文章站
2022-07-04 23:31:12
复制代码 代码如下: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..."
}
上一篇: Linux相关学习笔记-文件系统