PowerShell: Try...Catch...Finally 實現(xiàn)方法
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..."
}
相關(guān)文章
PowerShell查找分區(qū)中最大文件的方法(查找文件并按大小排序)
這篇文章主要介紹了PowerShell查找分區(qū)中最大文件的方法,查找文件并按占用空間排序,并用命令參數(shù)只輸出比如10條,這樣就可以快速找出一個目錄、一個分區(qū)下的N個最大的文件,需要的朋友可以參考下2014-08-08Powershell小技巧之使用Get-ChildItem得到指定擴展名文件
本文主要描述了使用Get-ChildItem得到指定擴展名文件的方法以及示例,并介紹了Get-ChildItem混合使用參數(shù)的問題,有需要的朋友可以參考下2014-09-09Powershell實現(xiàn)從注冊表獲取用戶配置腳本分享
這篇文章主要介紹了Powershell實現(xiàn)從注冊表獲取用戶配置腳本分享,本文直接給出實現(xiàn)腳本源碼,需要的朋友可以參考下2015-03-03Powershell小技巧之使用Copy-Item添加程序到開機啟動
本文主要記錄了本人安裝office2013后遇到的一個小需求,然后用powershell實現(xiàn)了這個功能,特此記錄下,并附上copy-item的使用方法2014-09-09powershell玩轉(zhuǎn)SQL SERVER所有版本的方法
微軟發(fā)布了最新的powershell for sql server 2016命令行客戶端庫。文章介紹了與之相關(guān)的實用方法,需要的朋友可以參考下2017-10-10