October 24, 2011 at 1:09 pm
I want to execute a Powershell script as a series of statement blocks. If an error occurs in a given statement block, then I want to stop execution of that block, record the error, and then continue on with the next block. I have set up the script like so:
Try
{ Statement1;
Statement2;
Statement3;
Statement4;
}
Catch
{ #Error Handling for Statements 1 through 4# }
Try
{ Statement5;
Statement6;
Statement7;
Statement8;
}
Catch
{ #Error Handling for Statements 5 through 8# }
Finally
{ #Script Cleanup Code# }
Here is what I want to happen: if an error occurs in Statement 3, then I want execution to stop and pass to the first catch block. Then I want execution to pick up with Statement 5 in the second try block.
My question is this: will it work the way I have set it up, or will an error in Statement 3 cause execution to pass to the first catch block, then bypass all of the statement in the second try block and the second catch block, before passing to the finally block?
I am unsure given the wording of the help documentation, and it is difficult for me to test what I am currently trying to do.
I appreciate your insight.
October 25, 2011 at 9:35 am
Worked for me as you had it.
Try
{ Write-Host "Statement 1"
Write-Host "Statement 2"
writ-host "Statement 3 Error"
Write-Host "Statement 4"
}
Catch
{ Write-Host "In first catch" }
Try
{ Write-Host "Statement 5"
Write-Host "Statement 6"
writ-host "Statement 7 error"
Write-Host "Statement 8"
}
Catch
{ Write-Host "In second catch" }
Finally
{ Write-Host "In Finally block" }
Those writ-host lines aren't typos, they're the errors to hit the Catch blocks.
October 25, 2011 at 10:26 am
Thank you! I have a very long script (that also takes a long time to run) with many blocks like this.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply