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.
It turns out this was trivial. I shouldn’t use Write-Error, but just output the exception directly:
and the output is:
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.