0

有一个命令(在 2008 盒子上)由于缓冲区限制而引发异常。

本质上,该脚本停止 WAUA,破坏 SoftwareDistribution,然后伸手重建 SD 并检查针对 WSUS 的更新,然后重新签入以使 WSUS 中的警报停止。

如果抛出异常,我想要一个特定的行重试,直到它完成而没有异常,然后我们可以告诉它向 WSUS 报告以清除它。

Stop-Service WUAUSERV
Remove-Item -Path C:\WINDOWS\SoftwareDistribution -recurse
Start-Service WUAUSERV
GPUpdate /force
WUAUCLT /detectnow
sleep 5

## This is the command I'd like to loop, if possible, when an exception is thrown ##
$updateSession = new-object -com "Microsoft.Update.Session"; $updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates

WUAUCLT /reportnow 

任何形式的帮助将不胜感激。我所能找到的一切都是如何创建自己的异常,而不是如何在抛出异常时处理它并重试直到它完成而没有错误。



编辑:

然后根据下面的答案,这是我希望它写成的方式,所以它会继续检查直到它成功运行然后它会重新报告?

Stop-Service WUAUSERV
Remove-Item -Path C:\WINDOWS\SoftwareDistribution -recurse
Start-Service WUAUSERV
GPUpdate /force
WUAUCLT /detectnow
sleep 5
while(-not $?) {$updateSession = new-object -com "Microsoft.Update.Session"; $updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates}
WUAUCLT /reportnow
4

2 回答 2

1

将值设置为 false 并且仅在获得完全成功时才翻转它。循环直到您成功或您的超时超过您定义的值——如果您不包括超时,您已经创建了一个无限循环条件,如果主机永远不会成功,它将运行直到重新启动。

$sts = $false
$count = 0
do {
    try {
        $updateSession = new-object -com "Microsoft.Update.Session"
        $updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates
        $sts = $true
    } catch {
        ## an exception was thrown before we got to $true
    }

    $Count++
    Start-Sleep -Seconds 1
} Until ($sts -eq $true -or $Count -eq 100)
于 2020-03-06T20:39:27.783 回答
1

您可以使用特殊字符$?如果最后一个命令返回错误,这将返回 false,因此您的 while 循环看起来像:

while(-not $?)

看看什么是美元?在PowerShell中。

或者,$error[0]给出最后抛出的错误消息,以便您可以围绕它构建一个 while 循环,类似于:

while($error[0] -ne "error message")
于 2020-03-06T19:54:56.323 回答