Created
October 12, 2024 04:09
-
-
Save Calvindd2f/b446f9ff2e28d38963beb3cdae18d809 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Format-StackTrace | |
| { | |
| param ( | |
| [Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
| [System.Management.Automation.ErrorRecord]$ErrorRecord, | |
| [switch]$RawOutput | |
| ) | |
| process | |
| { | |
| if (!$RawOutput) | |
| { | |
| $formatted = @(); | |
| $stackTrace = $ErrorRecord.ScriptStackTrace -split "`n" | |
| foreach ($line in $stackTrace) | |
| { | |
| if ($line -match 'at (.*), (.*): line (\d+)') | |
| { | |
| $function = $matches[1]; | |
| $script = $matches[2]; | |
| $lineNumber = $matches[3]; | |
| $formatted += "Function: $function`r`n" + | |
| "Script: $script`r`n" + | |
| "Line: $lineNumber`r`n" | |
| } | |
| } | |
| $formatted -join "`r`n"; | |
| } | |
| else | |
| { | |
| $error_record.Exception.ToString(); | |
| } | |
| } | |
| } | |
| ############## | |
| #### Tests | |
| ############## | |
| try { 1/0 } catch { $error_record = $_ }; $formatted_trace = $error_record | Format-StackTrace ; Write-Output $formatted_trace | |
| # Function: <ScriptBlock> | |
| # Script: <No file> | |
| # Line: 1 | |
| try { 1/0 } catch { $error_record = $_ }; $formatted_trace = $error_record | Format-StackTrace -RawOutput ; Write-Output $formatted_trace | |
| # System.Management.Automation.RuntimeException: Attempted to divide by zero. | |
| # ---> System.DivideByZeroException: Attempted to divide by zero. | |
| # --- End of inner exception stack trace --- | |
| # at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception) | |
| # at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame) | |
| # at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) | |
| # at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment