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

查看:14
本文介绍了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"

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

如果您经常需要多次重试操作的代码,您可以将循环的 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
}

或者像这样(如果您在某些情况下需要不同的重试次数):

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天全站免登陆