You are doing it wrong.
You already have a nice, big error message. Why on earth would you like to write code that checks $? obviously after each team? This is extremely cumbersome and error prone. Correct solution - stop checking $? ,
Instead, use the built-in PowerShell engine to blow you up. You turn it on, setting the error preference to the highest level:
$ErrorActionPreference = 'Stop'
I put this at the beginning of every script that I have ever written, and now I do not need to check $? This makes my code a lot easier and more reliable.
If you are faced with situations where you really need to disable this behavior, you can either catch error or pass the configuration of a specific function using the common -ErrorAction . In your case, you probably want your process to stop at the first error, catch the error, and then write it down.
Please note that this does not handle the case when external executables stop working (the completion code is non-zero, usually), so you still need to check $LASTEXITCODE if you call any of them. Despite this limitation, customization still saves a lot of code and effort.
Extra reliability
You may also consider using strict mode :
Set-StrictMode -Version Latest
This prevents PowerShell from running quietly when using a nonexistent variable and in other strange situations. (See -Version for details on what it restricts.)
The combination of these two settings makes PowerShell a much more fault-tolerant language, which greatly simplifies programming on it.
jpmc26 May 15 '18 at 20:40 2018-05-15 20:40
source share