You're way off track here.
You already have a nice, big error message. Why on Earth would you want to write code that checks $?
explicitly after every single command? This is enormously cumbersome and error prone. The correct solution is stop checking $?
.
Instead, use PowerShell's built in mechanism to blow up for you. You enable it by setting the error preference to the highest level:
$ErrorActionPreference = 'Stop'
I put this at the top of every single script I ever write, and now I don't have to check $?
. This makes my code vastly simpler and more reliable.
If you run into situations where you really need to disable this behavior, you can either catch
the error or pass a setting to a particular function using the common -ErrorAction
. In your case, you probably want your process to stop on the first error, catch the error, and then log it.
Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE
if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.
Additional reliability
You might also want to consider using strict mode:
Set-StrictMode -Version Latest
This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version
parameter for details about what it restricts.)
Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.