Skip to content

Instantly share code, notes, and snippets.

@Calvindd2f
Created October 12, 2024 04:09
Show Gist options
  • Select an option

  • Save Calvindd2f/b446f9ff2e28d38963beb3cdae18d809 to your computer and use it in GitHub Desktop.

Select an option

Save Calvindd2f/b446f9ff2e28d38963beb3cdae18d809 to your computer and use it in GitHub Desktop.
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