PowerShell: Try...Catch...Finally 實(shí)現(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中使用正則表達(dá)式跨行匹配字符串的方法
這篇文章主要介紹了PowerShell中使用正則表達(dá)式跨行匹配字符串的方法,重點(diǎn)在于正則表達(dá)式的寫法,需要的朋友可以參考下2014-08-08
PowerShell DSC組件 xExchange 發(fā)布
這篇文章主要介紹了PowerShell DSC組件 xExchange 發(fā)布,xExchange實(shí)現(xiàn)可以在PowerShell中使用DSC來部署和配置Exchange,需要的朋友可以參考下2015-04-04
PowerShell實(shí)現(xiàn)時(shí)間管理小秘書
這篇文章主要介紹了PowerShell實(shí)現(xiàn)時(shí)間管理小秘書,本文是一個(gè)PowerShell的綜合編程實(shí)例,實(shí)現(xiàn)了一個(gè)用來管理時(shí)間的功能,需要的朋友可以參考下2015-04-04

