Gill-Bates
Gill-Bates

Reputation: 679

How to leave Powershell Loop (while) after Success?

I want to execute a Powershell-Command until my command foo.bar successfull finished.

Therefore I have build a loop:

foo.bar -ErrorAction SilentlyContinue
            if (!$lastexitcode) {
                while (!$lastexitcode) {
                    Write-Output -InputObject "Retrying foo.bar in 2 Minutes ..."
                    Start-Sleep -Seconds 120
                    foo.bar -ErrorAction SilentlyContinue
                }
                    }

My Script is jumping into the loop, but will never leave it. So I'm runinng in a infinity-loop. Whats wrong?

Upvotes: 1

Views: 1312

Answers (2)

Gill-Bates
Gill-Bates

Reputation: 679

Thanks! This helped me out:

$maxretry = 3
while ($true -and $maxretry -gt 0) {
    foo.bar -ErrorAction SilentlyContinue
    if ($?) {
        break # Break the Loop on Success
    }
    else {
        $maxretry -= 1
        Write-Output -InputObject "foo.bar is still pending! Retrying for '$maxretry' times! Waiting for 2 Minutes ..."
        Start-Sleep -Seconds #120
    }
}

Upvotes: 0

marsze
marsze

Reputation: 17035

You could try the $? automatic variable. It will be true if the last command succeeded. I would simplify the loop like this:

while ($true) {
    foo.bar -ErrorAction SilentlyContinue
    if ($?) {
        # leave the loop on success
        break
    }
    # retry on error
    Write-Output -InputObject "Retrying foo.bar in 2 Minutes ..."
    Start-Sleep -Seconds 120
}

Note that this will not always work, it depends on how your foo.bar command handles the error action parameter. There could still be terminating errors so your if is never reached.

It might be more straight-forward to use a try-catch-construct:

while ($true) {
    try {
        foo.bar
        break
    }
    catch {
        Write-Output -InputObject "Retrying foo.bar in 2 Minutes ..."
        Start-Sleep -Seconds 120 
    }
}

Upvotes: 2

Related Questions