首页 > 解决方案 > Powershell 重试逻辑脚本审查

问题描述

我的要求是如果 $R 计数为 gt 0,那么我想暂停 5 秒然后再次执行 $R 并检查计数,像这样我想重试 5 次,如果我仍然看到 $R 计数,在 5 次尝试后gt 0 然后抛出错误。如果 $R count eq 0 则脚本应该从循环中退出而无需重试。

我已经尽了最大努力,但没有发生错误处理,有人可以在这里指导我..!

[int]$retry = 0

do 
{
  $Q = "exec ('DBCC opentran (TestDB)with tableresults')"
  $R = Invoke-Sqlcmd -ServerInstance "TESTSERVER" -Database "TESTDB" -Query $Q

  $count = $R.count
  Write-Host " count is $count" -ForegroundColor Yellow

  if ($count -gt 0)
  {
    $retry = $retry + 1

    Write-Host "retry count is  $retry"

    Start-Sleep -Seconds 5
    if ($retry -gt 5)
    {
      Write-Error "All the retry are finished..!"
    } 
  }
  else 
  {
    write-host "There are no open transactions !"
  }
} 
while ($count -gt 0)

标签: powershell

解决方案


这里的问题是你永远不会跳出循环。

Write-Error完全按照它所说的去做——它将一个错误写回调用者——但它不会停止正在运行的代码/脚本/函数/cmdlet的执行。

您可以将$ErrorActionPreference变量设置为Stop

$ErrorActionPreference = 'Stop'

如果您随后再次运行您的代码,您会发现只要Stop抛出错误,代码就会立即执行。

但是您的代码不应该依赖于偏好变量才能正常工作,因此这里真正的解决方案是确保您在出错时跳出循环:

    if ($retry -gt 5)
    {
      Write-Error "All the retry are finished..!"
      break          # this will stop the do-while loop
    } 

推荐阅读