您现在的位置是:网站首页> 编程资料编程资料
PowerShell: Try...Catch...Finally 实现方法_PowerShell_
2023-05-26
354人已围观
简介 PowerShell: Try...Catch...Finally 实现方法_PowerShell_
复制代码 代码如下:
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生成Windows密码算法简单学习_PowerShell_
- 探索PowerShell(十五) 引号与转义字符_PowerShell_
- 探索PowerShell(十四) 使用WMI对象的方法_PowerShell_
- 探索PowerShell(十三) WMI对象介绍_PowerShell_
- 探索PowerShell(十二) 筛选器 Filters_PowerShell_
- 探索PowerShell(十一)函数介绍_PowerShell_
- 探索PowerShell(十) 循环语句介绍_PowerShell_
- 探索PowerShell(九) 条件控制、逻辑_PowerShell_
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)_PowerShell_
- 探索PowerShell(七) PowerShell变量_PowerShell_
