Created
March 5, 2026 14:51
-
-
Save PanosGreg/b0a508ca293f796b95d964cd2ebc87ee to your computer and use it in GitHub Desktop.
Go through an Error Record recursively and get all exceptions and messages
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 Resolve-Error { | |
| [OutputType([object],[string])] # <-- by default [object], and [string] with AsString | |
| [CmdletBinding()] | |
| param ( | |
| [Parameter(ValueFromPipeline, Mandatory)] | |
| [ValidateNotNull()] | |
| $ErrorRecord, | |
| [switch]$AsString | |
| ) | |
| $List = [System.Collections.Generic.List[object]]::new() | |
| if ($ErrorRecord.psobject.Properties.Name.Contains('Exception')) { | |
| $List.Add([pscustomobject]@{ | |
| Level = 'Level0' | |
| Target = $ErrorRecord.Exception.TargetSite.Name | |
| Message = $ErrorRecord.Exception.Message | |
| }) | |
| } | |
| $InnerException = $ErrorRecord.Exception.InnerException | |
| $i = 1 | |
| while ([bool]$InnerException) { | |
| if ($InnerException.Message) { | |
| $List.Add([pscustomobject]@{ | |
| Level = "Level$i" | |
| Target = $InnerException.TargetSite.Name | |
| Message = $InnerException.Message | |
| }) | |
| } | |
| $i++ | |
| $InnerException = $InnerException.InnerException | |
| } | |
| if ($List.Count -ge 1) { | |
| $ToStringMethod = { | |
| if ($this.Target) {$Target = " .$($this.Target)() -"} | |
| else {$Target = [string]::Empty} | |
| '{0} |{1} {2}' -f $this.Level,$Target,$this.Message | |
| } | |
| $List | Add-Member -MemberType ScriptMethod -Name ToString -Value $ToStringMethod -Force | |
| } | |
| # reverse the list, start from the last (inner-most) exception and then move up to the (outer) exception | |
| $List.Reverse() | |
| if ($AsString) {($List | foreach {$_.ToString()} | Out-String).Trim()} | |
| else {Write-Output $List.ToArray()} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment