当前位置: 移动技术网 > IT编程>脚本编程>Shell > PowerShell: Try...Catch...Finally 实现方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网