Hey All, I"m just looking for some tips on best strategy for implementing error handling on a script that contains a few functions, which are called many times.
One of the functions is executed within a Foreach Loop, so it could execute many times (50 - 200). Anyway, I have error handling and alerting (fire off an email) embedded in the functions.
My first test of the script resulted in every execution of the function in the foreach loop firing off an email. That’s a problem.
As part of the error handling, I have each function writing their errors to an error log. I really just need a single email to notify me if the script failed or succeeded. I don’t need every error emailed as well.
I would say “it depends”. If each iteration of the loop is not depended on another iteration and you only want one failure notification I would just collect the error and the execution in some type of collection and a boolean indicating at least 1 failure occurred. Then after the loop send the notification of all failures.
Now if there are multiple steps in the loop that need to complete for a single execution (iteration) you could capture that with a try/catch/finally store the failure as mentioned before and continue to the next iteration. You can also try to correct the error in the catch and do some clean up in the finally block if needed
i’m with @neemobeer on this. Based on your description @FizzySoda I would be inclined to capture all the errors in a variable during loop execution, then afterwards if that variable exists send an email with that information concatenated.
An easy way to collect errors from different cmdlets is to use the -ErrorVariable parameter
Do-Something -ErrorVariable +errors
The + sign appends the errors, without it the variable would be overwritten with each command. Both the -OutVariable and -ErrorVariable parameters output [ArrayList] type collections.