I teach a PowerShell class and in a section on error handling, I discovered some strange behavior I can’t explain. Please help if you can explain what is happening and why. Consider the following 2 functions (contrived to illustrate the issue).
That is interesting, I thought it might be because of the addition sign in front of the error variable or on of the 2’s being construed as math, but even the changed code below shows the error variable containing 2 errors:
Although I don’t understand the relevance of “if (true)”, it should only execute a single time producing a single error, but I can reproduce what you are seeing in 5.1.17134.48.
Thanks all for the replies. After more investigation, I do believe this is a bug. I found in Don Jones Big Book of PowerShell Error Handling , “As soon as terminating errors enter the picture, however, ErrorVariable has some very annoying behavior: it sometimes contains Exception objects instead of ErrorRecords, and in many cases, has one or more duplicate objects all relating to the terminating error.” I believe this is the case in the code as it is producing duplicate objects relating to the terminating error. I posted a bug report in the Windows site. If I can verify it produces the same result in PS V6, I could post on GitHub as well. If you would like to vote this issue up on the Windows site, you can here https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/34266901-terminating-error-in-if-statement-script-block-gen
It is a fresh console in the code provided, but I can add
rv 1var, 2var
before calling the functions to continue testing without closing the shell and get the same result. It produces 2 identical ErrorRecord objects in the $2var variable but only one in $Error. I believe this may be a bug. I wanted to be sure there wasn’t something I was missing before chalking it up to that, because I couldn’t find a bug report already ID’d at Microsoft or GitHub for this specific issue.