PowerShell: Try...Catch...Finally 实现方法
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查找分区中最大文件的方法,查找文件并按占用空间排序,并用命令参数只输出比如10条,这样就可以快速找出一个目录、一个分区下的N个最大的文件,需要的朋友可以参考下2014-08-08Powershell小技巧之使用Get-ChildItem得到指定扩展名文件
本文主要描述了使用Get-ChildItem得到指定扩展名文件的方法以及示例,并介绍了Get-ChildItem混合使用参数的问题,有需要的朋友可以参考下2014-09-09Powershell小技巧之使用Copy-Item添加程序到开机启动
本文主要记录了本人安装office2013后遇到的一个小需求,然后用powershell实现了这个功能,特此记录下,并附上copy-item的使用方法2014-09-09
最新评论