PowerShell尝试/捕获并重试 [英] PowerShell Try/Catch and Retry

查看:136
本文介绍了PowerShell尝试/捕获并重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大的Powershell脚本,其中包含许多(20+)个函数,可以执行各种操作。

I have a fairly large powershell scripts with many (20+) functions which perform various actions.

现在,所有代码实际上都没有任何错误处理或重试功能。如果特定任务/功能失败,它只会失败并继续。

Right now all of the code doesn't really have any error handling or retry functionality. If a particular task/function fails it just fails and continues on.

我想改善错误处理并执行重试以使其更强大。

I would like to improve error handling and implement retries to make it more robust.

我在想类似的东西:

$tries = 0
while ($tries -lt 5) {
    try{    

       # Do Something

       # No retries necessary
       $tries = 5;
    } catch {
       # Report the error
       # Other error handling
    }
 }

问题是我需要执行许多步骤。

The problem is that I have many many steps where I would need to do this.

我认为实施上述代码20次没有任何意义。似乎真的是多余的。

I don't think it make sense to implement the above code 20 times. That seems really superfluous.

我正在考虑编写一个带有包含要调用的实际函数的参数的 TryCatch函数?

I was thinking about writing an "TryCatch" function with a single parameter that contains the actual function I want to call?

我也不知道这是正确的方法。我不会以一个脚本读取最终结果:

I'm not sure that's the right approach either though. Won't I end up with a script that reads something like:

TryCatch "Function1 Parameter1 Parameter2"
TryCatch "Function2 Parameter1 Parameter2"
TryCatch "Function3 Parameter1 Parameter2"

是否有更好的方法

推荐答案

如果您经常需要多次重试操作的代码,则可以包装循环的 try..catch 并在脚本块中传递命令:

If you frequently need code that retries an action a number of times you could wrap your looped try..catch in a function and pass the command in a scriptblock:

function Retry-Command {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [scriptblock]$ScriptBlock,

        [Parameter(Position=1, Mandatory=$false)]
        [int]$Maximum = 5,

        [Parameter(Position=2, Mandatory=$false)]
        [int]$Delay = 100
    )

    Begin {
        $cnt = 0
    }

    Process {
        do {
            $cnt++
            try {
                $ScriptBlock.Invoke()
                return
            } catch {
                Write-Error $_.Exception.InnerException.Message -ErrorAction Continue
                Start-Sleep -Milliseconds $Delay
            }
        } while ($cnt -lt $Maximum)

        # Throw an error after $Maximum unsuccessful invocations. Doesn't need
        # a condition, since the function returns upon successful invocation.
        throw 'Execution failed.'
    }
}

调用像这样的功能(默认为5次重试):

Invoke the function like this (default is 5 retries):

Retry-Command -ScriptBlock {
    # do something
}

或类似这样(如果您在某些情况下需要不同的重试次数): / p>

or like this (if you need a different amount of retries in some cases):

Retry-Command -ScriptBlock {
    # do something
} -Maximum 10

该功能可以进一步改进,例如通过使 $ Maximum 失败尝试后脚本终止可以使用另一个参数进行配置,这样您就可以执行将导致脚本在失败时停止的操作,以及失败可以忽略。

The function could be further improved e.g. by making script termination after $Maximum failed attempts configurable with another parameter, so that you can have have actions that will cause the script to stop when they fail, as well as actions whose failures can be ignored.

这篇关于PowerShell尝试/捕获并重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆