亲宝软件园·资讯

展开

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

人气:0
想了解PowerShell: Try...Catch...Finally 实现方法的相关内容吗,在本文为您仔细讲解Try...Catch...Finally 的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Try,Catch,Finally,下面大家一起来学习吧。

复制代码 代码如下:

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

加载全部内容

相关教程
猜你喜欢
用户评论