欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-04 23:31:12
复制代码 代码如下:function try    {        p...

复制代码 代码如下:

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