gpt4 book ai didi

PowerShell 尝试/捕获并重试

转载 作者:行者123 更新时间:2023-12-02 22:41:33 35 4
gpt4 key购买 nike

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

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

我想改进错误处理并实现重试以使其更加健壮。

我在想类似的事情:

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

# Do Something

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

问题是我有很多步骤需要执行此操作。

我认为上面的代码执行20次是没有意义的。这看起来确实是多余的。

我正在考虑编写一个带有单个参数的“TryCatch”函数,其中包含我想要调用的实际函数?

但我也不确定这是否是正确的方法。我最终会不会得到一个如下所示的脚本:

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

有更好的方法吗?

最佳答案

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

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 {
# If you want messages from the ScriptBlock
# Invoke-Command -Command $ScriptBlock
# Otherwise use this command which won't display underlying script messages
$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 次):

Retry-Command -ScriptBlock {
# do something
}

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

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

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

关于PowerShell 尝试/捕获并重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45470999/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com