2

Consider the following snippet:

function fail {
    throw "simulated failure"
}
fail

When running the script, the default exception handling prints the line and command where the exception was thrown:

simulated failure
At D:\tmp\Untitled1.ps1:2 char:10
+     throw <<<<  "simulated failure"
    + CategoryInfo          : OperationStopped: (simulated failure:String) [],     RuntimeException
    + FullyQualifiedErrorId : simulated failure

On the other hand, if I catch the exception and print it myself:

function fail {
    throw "simulated failure"
}
try {
    fail
} catch {
    Write-Error $_
    exit 1
}

the output of Write-Error only tells me that the error happened inside the script:

D:\tmp\Untitled2.ps1 : simulated failure
At line:1 char:16
+ .\Untitled2.ps1 <<<<
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Untitled2.ps1

How can I achieve the same output as in the first case?

NOTE: The reason I want to catch the exception is to do "exit 1". By default powershell exits with 0 even after exceptions, so the script appears to have been successful.

Bogdan Calmac
  • 7,993
  • 6
  • 51
  • 64

1 Answers1

4

It turns out this was trivial. I shouldn't use Write-Error, but just output the exception directly:

function fail {
    throw "simulated failure"
}
try {
    fail
} catch {
    $_
    exit 1
}

and the output is:

simulated failure
At D:\tmp\Untitled2.ps1:2 char:14
+         throw <<<<  "simulated failure"
    + CategoryInfo          : OperationStopped: (simulated failure:String) [], RuntimeException
    + FullyQualifiedErrorId : simulated failure

UPDATE:

This approach obviously writes to output stream. If you want to write to the error stream instead (as Write-Error does) you are probably out of luck, according to this post: How do I write to standard error in PowerShell?. Write-Error cannot be used to write a specific string (it adds its own stuff) and there's no equivalent of Write-Error that deals nicely with redirection. I would personally love to see an Out-Error cmdlet that mimics Out-Default but writes to the error stream of the current pipeline element.

Community
  • 1
  • 1
Bogdan Calmac
  • 7,993
  • 6
  • 51
  • 64
  • Bumping into the same issue unfortunately. Do you happen to know if there's currently an equivalent of Write-Error that deals with redirection? – Lieven Keersmaekers Oct 21 '16 at 09:15