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.