Anthony Lombardi
Anthony Lombardi

Reputation: 33

Powershell -- Command throws exception, retry previous command (loops) until successful

Have a command that (on 2008 boxes) throws an exception due to the buffer limit.

Essentially, the script stops WAUA, blows out SoftwareDistribution, then reaches out to rebuild SD and check for updates against WSUS then checks back in so the alerts in WSUS stop.

I want a specific line to retry if an exception is thrown until it finishes without an exception, then we can tell it to report back in to WSUS to clear it out.

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 

Any kind of help would be appreciated. Everything I've been able to find has been how to create my own exception but not how to handle it when an exception is thrown and retry until it finishes without an error.



Edit:

Then based on the below Answer, is this how I would want it to be written so it will continue to check until it runs successfully and then it'll report back in?

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

Upvotes: 0

Views: 597

Answers (2)

thepip3r
thepip3r

Reputation: 2935

Set a value to false and only flip it if you get total success. Loop until you succeed or your timeout exceeds your defined value -- if you don't include a timeout, you have created an infinite loop condition where if the host never succeeds, it'll run until reboot.

$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)

Upvotes: 1

AutomatedOrder
AutomatedOrder

Reputation: 500

You can use the special character $? This will return false if the last command returned with error, so your while loop would just look like:

while(-not $?)

See what is $? in powershell.

Alternatively, $error[0] gives the last thrown error message so you could build a while loop around that, similar to:

while($error[0] -ne "error message")

Upvotes: 1

Related Questions