首页 > 开发 > PowerShell > 正文

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

2020-10-29 21:09:47
字体:
来源:转载
供稿:网友

复制代码 代码如下:

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表