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

Roxana ·
更新时间:2024-09-20
· 740 次阅读

代码如下:
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..."
    }

您可能感兴趣的文章:try catch finally的执行顺序深入分析C#中的try catch finally用法分析理解javascript中try...catch...finally杂谈try-catch-finally异常处理再谈异常处理try catch finally



try PowerShell

需要 登录 后方可回复, 如果你还没有账号请 注册新账号