powershell - 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)
解决方案
这里的问题是你永远不会跳出循环。
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
}
推荐阅读
- amazon-web-services - Amazon Athena 视图实际上是 Hive 视图,还是单独的附加视图?
- r - 试图查看一个变量的一个级别在另一个变量的另一个级别中有多少
- php - base.html.twig symfony2 中的订单通知列表
- c# - .Add 触发 RoutedEvent="Loaded" 但 .Insert 没有
- html - 如何创建一个包含两个具有不同不透明度的内部嵌入 imgclass 项目的表?
- excel - 未选中复选框时出现运行时错误 13
- javascript - 为贪吃蛇游戏添加高分
- algorithm - 在 SQL 之外使用 HLL_COUNT.MERGE
- c# - 如何执行WebClient?
- python - RegEx 用于捕获和替换字符串中除特殊模式外的所有数字