daand
daand

Reputation: 11

Powershell: Trap continue breaks entire loop

Trying to create a better way to handle errors for some automated stuff.

My understanding is that, when using "continue" in Trap, it should just keep looping, but skip the rest of the current iteration. However, in the following code, everything handle as I expect, except in the loop, code completely stops, and no matter what I try I can't get it to keep looping.

trap {
   Clear-Host
   Write-Host "Running script: '$PSCommandPath' as user: '$(whoami)' with process id (PID): '$PID'`n"
   Write-Host "Exception error: " $_
   Write-Host "`nVariables at run time:"
   Get-Variable *
   continue;
}

try {
    throw "TryCatchError"
} catch { Write-Host "test 2 caught" $_ }

throw "TrapError"

#this loop doesnt work
While ($true) { Throw "error"; Start-sleep 1}

Can anybody explain why or have a solution that would let the loop continue, while still trapping (not try/catching) the error?

Upvotes: 1

Views: 660

Answers (1)

Daniel Björk
Daniel Björk

Reputation: 2507

Based on the comment I did the way I would do it is handle this is using a try-catch statement since thats the correct way to do it. This will continue your while-statement gracefully and ignore the Start-sleep 1; row.

While ($true) { 
    try {
            Throw "error"; 
    }
    catch {
       Clear-Host
       Write-Host "Running script: '$PSCommandPath' as user: '$(whoami)' with process id (PID): '$PID'`n"
       Write-Host "Exception error: " $_
       Write-Host "`nVariables at run time:"
       Get-Variable *
        continue;
    }

    Start-sleep 1; 
}

Upvotes: 0

Related Questions