How can I write to standard error from PowerShell, or trap errors such that:
- An error message is displayed as an error (truly writing to standard error so that TeamCity and Octopus see it as an error)
- No stack trace garbage muddles my beautiful, concise error message
All these years I've survived by throw
ing errors or writing via Write-Error
, but I'm tired and old, and in my scripts I just want to see one concise error message. I've been trying every combination of trap
, throw
, Write-Error
, and -ErrorAction
, to no avail:
try {
throw "error" # Sample code for a stack overflow. In the theater
# of your mind, imagine there is code here that does something real and useful
} catch {
Write-Error "An error occurred attempting to 'do something.' Have you tried rebooting?"
}
Here's the user experience I want to see:
C:\> & .\Do-Something.ps1
An error occurred attempting to 'do something.' Have you tried rebooting?
C:\> ▏
Instead I get:
C:\> & .\Do-Something.ps1
An error occurred attempting to 'do something.' Have you tried rebooting?
At line:1 char:1
+ Do-RealWork
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Do-RealWork
C:\> ▏