脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - PowerShell - PowerShell: Try...Catch...Finally 实现方法

PowerShell: Try...Catch...Finally 实现方法

2020-05-28 11:33脚本之家 PowerShell

PowerShell 本身有很多很好的错误控制,但是习惯于.net编程的人员,更喜欢用Try Catch Finally方法,尤其当有一段代码必须被执行到的时候。现在好了,adweigert 想出了一个好方法来实现。这个函数已经在多种情况下测试过,希望能对你

复制代码 代码如下:


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..."
    }

 

延伸 · 阅读

精彩推荐