powershellerror-handlingstderrexit-code

How can I display a 'naked' error message in PowerShell without an accompanying stacktrace?


How can I write to standard error from PowerShell, or trap errors such that:

All these years I've survived by throwing 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:\> ▏

Solution

  • Preface re what doesn't work:


    Provided that your PowerShell code is run from a console (uses a console host), use [Console]::Error.WriteLine(), which unconditionally writes to the outside world's stderr (standard error stream):

    [Console]::Error.WriteLine("An error occurred ... Have you tried rebooting?")
    

    Note:


    Sadly, there is no single solution that works both from within PowerShell (across hosts) and from outside of it:


    [1] Peter (the OP himself) offers a workaround for that:

    [Console]::ForegroundColor = 'red'
    [Console]::Error.WriteLine("An error occurred ... Have you tried rebooting?")
    [Console]::ResetColor()
    

    suneg's helpful answer provides a function wrapper for it.

    Fortunately, PowerShell automatically omits the color codes when it detects that the output is being redirected (to a file).