I've read about differences of echo (which is a Write-Output) and Write-Error but I have still issues with exceptions and stack traces.
The following sample demonstrates my issue:
$ErrorActionPreference = "stop"
trap {
echo "Trap encountered. Exiting with 1. See errors below."
echo $_ # This is a test
Write-Error -ErrorRecord $_
exit 1
}
BROKEN_COMMAND
I won't post the output as it is localized but the gist is:
echooutputs "BROKEN_COMMAND" was not found to be a CmdLet etc and outputs the callstack of the exact location where the issue was found, above would be line 10 or so.Write-Erroroutputs the line "BROKEN_COMMAND" was not found to be a CmdLet too but then the callstack shows actually the line where the Write-Error statement is and not the proper callstack (line 5)
How can I properly write to the error channel? I've tried omitting -ErrorRecord but no effect.
I need the error channel for errors so dumping everything in echo and then writing "there has been an error" in the error channel is not a good option.
Update: I tested @MathiasR.Jessen hint with throw (actually throw $_).
This results however in an immediate exit of the program without a useful exit code in $LASTEXITCODE, which I require to properly signal the end. My exit 1 is not executed and the throw terminates without proper exit code.
throw(with no arguments) instead ofWrite-Error $_if you want to preserve the original callstackthrow $_however fixed it :) I did not think about throw as I was in the trap and assumed recursion here.throw $_since it exits my program there is no proper exit code specified, and I need exit codes when exceptions exit, this is quirky powershell behaviour.