-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSV.DebugTraceTools.ps1
More file actions
1599 lines (1377 loc) · 53.1 KB
/
PSV.DebugTraceTools.ps1
File metadata and controls
1599 lines (1377 loc) · 53.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Title : PSV.DebugTraceTools.ps1
Author : Jon Damvi
Version : 1.0.1
Date : 02.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (19.05.2025) - initial release (by Jon Damvi).
v1.0.1 (02.06.2025) - synopsis function documentation (by Jon Damvi).
.DESCRIPTION
Shows detailed Exception Error Trace information
.INPUTS
None.
.OUTPUTS
None.
#>
Class ActualError {
[int]$HResult
[string]$HResultHex
[string]$Facility
[int]$FacilityCode
[int]$ErrorCode
[bool]$IsFailure
[string]$Message
}
<#
.SYNOPSIS
Title : Function Get-ActualError
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
Translates decimal exception HResult error code to actual error information.
.PARAMETER hresult
(Optional) Specifies HResult error code to decode.
Expected type: [int]
.INPUTS
None
.OUTPUTS
ActualError - Class-object containing detailed error information.
.EXAMPLE
[ActualError]$ErrorInfo = Get-ActualError -hresult -2146233087
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
function Get-ActualError {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[int]$HResult
)
# Define a class to hold the decoded error info
Class ActualError {
[int]$HResult
[string]$HResultHex
[string]$Facility
[int]$FacilityCode
[int]$ErrorCode
[bool]$IsFailure
[string]$Message
}
$ActualError = [ActualError]::new()
$ActualError.HResult = $HResult
$ActualError.HResultHex = "0x" + $HResult.ToString("X8")
# Extract error code (lowest 16 bits)
$ActualError.ErrorCode = $HResult -band 0xFFFF
# Extract facility code (bits 16-30)
$ActualError.FacilityCode = ($HResult -shr 16) -band 0x1FFF
# Check if severity bit (bit 31) is set (failure)
$ActualError.IsFailure = ($HResult -band 0x80000000) -ne 0
# Get the Win32 error message corresponding to the HRESULT
Try {
$ActualError.Message = (New-Object System.ComponentModel.Win32Exception($HResult)).Message
} Catch {
$ActualError.Message = "Unknown error message"
}
# Map facility codes to names based on standard HRESULT facility codes
switch ($ActualError.FacilityCode) {
0 { $ActualError.Facility = 'FACILITY_NULL' }
1 { $ActualError.Facility = 'FACILITY_RPC' }
2 { $ActualError.Facility = 'FACILITY_DISPATCH' }
3 { $ActualError.Facility = 'FACILITY_STORAGE' }
4 { $ActualError.Facility = 'FACILITY_ITF' }
5 { $ActualError.Facility = 'FACILITY_WIN32' }
6 { $ActualError.Facility = 'FACILITY_WINDOWS' }
7 { $ActualError.Facility = 'FACILITY_SSPI' }
default { $ActualError.Facility = 'UNKNOWN' }
}
return $ActualError
}
<#
.SYNOPSIS
Title : Function Get-ActiveScopeCount
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
Gets count of active powershell scopes excluding console and global session scope.
.INPUTS
None
.OUTPUTS
System.Byte - count of active powershell scopes.
.EXAMPLE
Get-ActiveScopeCount
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Get-ActiveScopeCount {
[CmdletBinding()]
Param()
[byte]$Count = 0
While ($true) {
Try {
# Try to get reserved variable at scope $count. This function call limits processing overhead to minimum as possible.
Get-Variable -Name 'PID' -ValueOnly -Scope $Count -ErrorAction Stop -WarningAction SilentlyContinue -InformationAction SilentlyContinue -Verbose:$false | Out-Null
$Count++
}
Catch {
break
}
}
return [byte]($Count-2)
}
<#
.SYNOPSIS
Title : Function Get-LocalSetVariables
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER Scope
(Mandatory) Specifies ...
Expected type : [Byte]
Allowed Values : [0;255]
Default Value : 0
.INPUTS
None
.OUTPUTS
System.Management.Automation.PSVariable[]
.EXAMPLE
# Usage Case ... Example Description :
PS > Get-LocalSetVariables -Scope $Scope
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Get-LocalSetVariables {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateRange(0,255)]
[byte]$Scope = 0
)
# Scope = 0 - value is for the user
# ActualScope is one level back from 0
[byte]$ActualScope = $Scope + 1
If($ActualScope -ge $(Get-ActiveScopeCount -ErrorAction Stop)) {
return
}
# Known automatic variables to exclude
[string[]]$FilterVars = @(
'null', 'PSBoundParameters', 'PSCommandPath', 'PSCulture', 'PSDefaultParameterValues',
'PSEmailServer', 'PSHome', 'PSItem', 'PSModuleAutoLoadingPreference', 'PSScriptRoot', 'PSSessionApplicationName',
'PSSessionConfigurationName', 'PSSessionOption', 'PSUICulture', 'PSVersionTable', 'StackTrace', 'This',
'VerbosePreference', 'WarningPreference', 'DebugPreference', 'ErrorActionPreference', 'InformationPreference',
'ConfirmPreference', 'WhatIfPreference', 'MaximumAliasCount', 'MaximumDriveCount', 'MaximumErrorCount',
'MaximumFunctionCount', 'MaximumHistoryCount', 'MaximumVariableCount', 'NestedPromptLevel', 'OutputEncoding',
'ProgressPreference', 'PWD', 'Home', 'Host', 'PID', 'ExecutionContext', 'MyInvocation', 'PSDefaultParameterValues',
'PSModulePath', 'PSProvider', 'PSCommandPath', 'PSCulture', 'PSHOME', 'PSUICulture', 'PSCmdlet', '_'
)
# Flags for Constant and AllScope
[int]$ExcludeFlags = [int](2 -bor 8)
# Get local variables excluding Constant and AllScope
[System.Management.Automation.PSVariable[]]$LocalVars = [System.Management.Automation.PSVariable[]]@(
Get-Variable -Scope $ActualScope | ? { ([int]$_.Options -band $ExcludeFlags) -eq 0 }
)
# Exclude known automatic variables by name
[System.Management.Automation.PSVariable[]]$FilteredVars = [System.Management.Automation.PSVariable[]]@(
$LocalVars.GetEnumerator() | ? { $FilterVars -notcontains $_.Name }
)
[System.Management.Automation.PSVariable[]]$result = [System.Management.Automation.PSVariable[]]@(
$FilteredVars.GetEnumerator() | ? {
[System.Management.Automation.PSVariable]$ParentVar = [System.Management.Automation.PSVariable](
Get-Variable -Name $_.Name -Scope Script -ErrorAction SilentlyContinue
)
If ($null -eq $ParentVar) {
$true
}
Else {
$_.Value -ne $ParentVar.Value
}
}
)
return [System.Management.Automation.PSVariable[]]$result
}
<#
.SYNOPSIS
Title : Function Format-TraceInfo
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER Message
(Mandatory) Specifies ...
Expected type: [String]
.PARAMETER EntryPoint
(Mandatory) Specifies ...
Expected type: [SwitchParameter]Aliases: Entry
.PARAMETER TransitivePoint
(Mandatory) Specifies ...
Expected type: [SwitchParameter]Aliases: Transitive
.PARAMETER Scope
(Optional) Specifies ...
Expected type: [Byte]
Allowed Values: [0;255]
Default Value: 0
.INPUTS
None
.OUTPUTS
$TraceMessage - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Format-TraceInfo -Message $Message -EntryPoint $EntryPoint -TransitivePoint $TransitivePoint -Scope $Scope
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Format-TraceInfo {
[CmdletBinding(DefaultParameterSetName = 'TransitivePoint')]
Param(
[Parameter(Mandatory)]
[string]$Message,
[Parameter(Mandatory, ParameterSetName = 'EntryPoint')]
[Alias('Entry')]
[switch]$EntryPoint,
[Parameter(Mandatory, ParameterSetName = 'TransitivePoint')]
[Alias('Transitive')]
[switch]$TransitivePoint,
[Parameter()]
[ValidateRange(0,255)]
[byte]$Scope = 0
)
Try {
[byte]$ActualScope = $Scope + 1
If($ActualScope -ge $(Get-ActiveScopeCount -ErrorAction Stop)) {
return
}
# Function body as before, using $PSCmdlet.ParameterSetName to branch logic
$CallStack = @(Get-PSCallStack -ErrorAction Stop)
$CallStackScope = $ActualScope
If($CallStack.Count -le $CallStackScope) {
return
}
$CurrentFunction = $CallStack[$CallStackScope].FunctionName
$InvocationName = $CallStack[$CallStackScope].InvocationInfo.InvocationName
$AliasUsed = ($InvocationName -And $InvocationName -ne $CurrentFunction)
$EntryPointName = "${CurrentFunction}"
If ($AliasUsed) {
$EntryPointName = "#$InvocationName->${CurrentFunction}"
}
# Build call stack string only if in Params set
$CallStackStr = ''
If ($PSCmdlet.ParameterSetName -eq 'EntryPoint') {
$FilteredStack = @($CallStack[$CallStackScope..($CallStack.Count-1)] | % {
If ($_.FunctionName -eq "<ScriptBlock>") { "<Script>" }
Else {
If ($_.InvocationInfo.InvocationName -And $_.InvocationInfo.InvocationName -ne $_.FunctionName -And $_.FunctionName -notmatch '.+<(Begin|Process|End)>') {
"#$([string]$_.InvocationInfo.InvocationName)->[$([string]$_.FunctionName)]"
}
Else {
[string]$_.FunctionName
}
}
})
[Array]::Reverse($FilteredStack)
$CallStackStr = $FilteredStack -join ':'
}
# Format items (Params or Locals)
$Params = $CallStack[$CallStackScope].InvocationInfo.BoundParameters
Switch ($PSCmdlet.ParameterSetName) {
'EntryPoint' {
$items = $Params
}
'TransitivePoint' {
$items = @{}
$VariableScope = $ActualScope
$LocalVariables = @(
Get-LocalSetVariables -Scope ($VariableScope) -ErrorAction Stop
) | ? {
(-Not $Params.ContainsKey($_.Name) -OR $Params[$_.Name] -ne $_.Value)
}
Foreach ($var in $LocalVariables) {
$items[$var.Name] = $var.Value
}
}
default {
$items = @{}
}
}
# Format items using your Format-Value helper
$ItemStrings = @(Foreach ($key in $items.Keys | Sort) {
$Value = $items[$key]
"${key} = " + (Format-Value $Value -ErrorAction Stop)
})
$ItemsStr = If ($ItemStrings.Count) { $ItemStrings -join ", `n " } Else { '' }
# Determine line number if call stack available
$LineNum = $CallStack[$CallStackScope].ScriptLineNumber
If ($PSCmdlet.ParameterSetName -eq 'EntryPoint') {
$ItemsStr = "(`n $ItemsStr`n)"
} Else {
$ItemsStr = "`n $ItemsStr`n"
}
$TraceMessage = ''
If ($PSCmdlet.ParameterSetName -eq 'EntryPoint') {
$TraceMessage = "[${EntryPointName}]: '${Message}' (Line:${LineNum}): ${CallStackStr}${ItemsStr}"
} Else {
$TraceMessage = "[${EntryPointName}]: '${Message}' (Line:${LineNum}): `n{${CallStackStr}${ItemsStr}}"
}
return $TraceMessage
}
Catch {
Throw $_
}
}
<#
.SYNOPSIS
Title : Function Format-Value
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER Value
(Optional) Specifies ...
Expected type: [Object]
.INPUTS
None
.OUTPUTS
[string] - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Format-Value -Value $Value
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Format-Value {
[CmdletBinding()]
Param(
[Object]$Value
)
$MaxLength = 255
[string]$ReturnStr = ''
If ($null -eq $Value) {
$ReturnStr = '`$null'
}
ElseIf (($Value -is [switch]) -OR ($Value -is [bool])) {
$ReturnStr = $Value.ToString().ToLower()
}
ElseIf ($Value -is [string] -OR $Value -is [ScriptBlock]) {
If ($Value -is [ScriptBlock]) { $Value = $Value.ToString() }
$Str = $Value.TrimStart(" ", "`n", "`r")
# Get up to first newline or $MaxLength, whichever is shorter
$NewlineIdx = $Str.IndexOf("`n")
If ($NewlineIdx -ge 0 -And $NewlineIdx -lt $MaxLength) {
$Preview = $Str.Substring(0, $NewlineIdx).TrimEnd(" ", "`r", "`n")
$ReturnStr = '"' + $Preview + ' \\~..."'
} ElseIf ($str.Length -gt $MaxLength) {
$Preview = $Str.Substring(0, $MaxLength).TrimEnd(" ", "`r", "`n")
$ReturnStr = '"' + $Preview + ' ~..."'
} Else {
$ReturnStr = '"' + $Str + '"'
}
}
ElseIf ($Value.GetType().IsPrimitive) {
return $Value.ToString()
}
ElseIf ($Value -is [System.Array]) {
$TypeName = $Value.GetType().GetElementType().Name
$Count = $Value.Count
$ReturnStr = "[$TypeName[$Count]]`$Obj"
}
Else {
Try {
$ValueString = $Value.ToString()
$ValueTypeFullName = $Value.GetType().FullName
If ($ValueString -ne $ValueTypeFullName) {
$ReturnStr = "'" + $ValueString + "'"
}
} Catch {
}
$ValueTypeName = $Value.GetType().Name
$ReturnStr = "[$ValueTypeName]`$Obj"
}
return $ReturnStr
}
<#
.SYNOPSIS
Title : Function Get-ErrorStackTrace
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorStackTrace
(Mandatory) Specifies ...
Expected type: [String]
.INPUTS
None
.OUTPUTS
None
.EXAMPLE
# Usage Case ... Example Description :
PS > Get-ErrorStackTrace -ErrorStackTrace $ErrorStackTrace
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Get-ErrorStackTrace {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ErrorStackTrace
)
[Hashtable[]]$ErrorTraces = @()
$StackTraceMatches = Select-String '[A-Z]+ ([^,]+), ([A-Z]:\\[^:]+|[^:]+): [A-Z]+ ([\d]+)' -Input $StackTrace -AllMatches
If($StackTraceMatches -And $StackTraceMatches.Matches) {
Foreach($StackTraceMatch in $StackTraceMatches.Matches) {
$ErrorTrace = @{}
$StackFuncName = $StackTraceMatch.Groups[1].Value
$ErrorTrace['StackFuncName'] = $(If ($StackFuncName -ne '<ScriptBlock>') { $StackFuncName } Else { '<Script>' })
$ScriptPath = $StackTraceMatch.Groups[2].Value
$ScriptPathShort = ''
$ScriptName = ''
If (Test-Path $ScriptPath -IsValid) {
$ScriptName = Split-Path $ScriptPath -Leaf -ErrorAction Stop
$ScriptPathShort = "...\$ScriptName"
}
$ErrorTrace['ScriptPath'] = $ScriptPath
$ErrorTrace['ScriptName'] = $ScriptName
$ErrorTrace['ScriptPathShort'] = $ScriptPathShort
$ErrorTrace['LineNum'] = $StackTraceMatch.Groups[3].Value
$ErrorTraces += $ErrorTrace
}
}
[Hashtable[]]::Reverse($ErrorTraces)
return $ErrorTraces
}
<#
.SYNOPSIS
Title : Function Format-ErrorPositionMessage
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER PositionMessage
(Mandatory) Specifies ...
Expected type: [String]
.INPUTS
None
.OUTPUTS
$result - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Format-ErrorPositionMessage -PositionMessage $PositionMessage
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Format-ErrorPositionMessage {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$PositionMessage
)
[string]$result = ''
If ($PositionMessage -match '.+\.ps1:.+\n') {
$PosLines = $PositionMessage.Split("`n")
If ($PosLines[0] -match '^([^ ]+ )([A-Z]:\\[^:]+|[^:]+)(:.+)$') {
$PosPrefix = $Matches[1]
$PosPath = $Matches[2]
$PosEnding = $Matches[3]
If(Test-Path $PosPath -IsValid) {
$PosLines[0] = "$PosPrefix ...\$(Split-Path $PosPath -Leaf -ErrorAction Stop)$PosEnding"
$result = $PosLines -join "`n"
}
}
}
return [string]$result
}
<#
.SYNOPSIS
Title : Function Parse-ErrorDetails
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorRecord
(Optional) Specifies ...
Expected type: [ErrorRecord]
.PARAMETER Exception
(Mandatory) Specifies ...
Expected type: [Object]
.INPUTS
None
.OUTPUTS
$ErrFields - returned when ...
$null - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Parse-ErrorDetails -ErrorRecord $ErrorRecord -Exception $Exception
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Parse-ErrorDetails {
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[System.Management.Automation.ErrorRecord]$ErrorRecord,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[Object]$Exception
)
If ($null -eq $ErrorRecord -And $null -eq $Exception) { return $null }
[Hashtable]$ErrFields = @{}
If($Exception) {
$ErrFields['Message'] = Get-ObjectFieldValue -FieldName 'Message' -Object $Exception -ErrorAction Stop
$ErrCodeD = Get-ObjectFieldValue -FieldName 'HResult' -Object $Exception -ErrorAction Stop
$ErrFields['ErrCodeD'] = $ErrCodeD
$ErrFields['ErrCodeH'] = $(If ($ErrCodeD) { "0x{0:X8}" -f $ErrCodeD })
$ErrFields['Win32ErrMsg'] = $(If ($ErrCodeD) { $Msg = $(Get-ActualError $ErrCodeD -ErrorAction Stop).Message; $(If ($Msg -notmatch "Unknown Error \(") { $Msg }) })
$ErrData = Get-ObjectFieldValue -FieldName 'Data' -Object $Exception -ErrorAction Stop
$ErrFields['ThrowManual'] = $false
If($ErrData) {
$ErrFields['ThrowManual'] = Get-ObjectFieldValue -FieldName 'ThrowManual' -Object $ErrData -ErrorAction Stop
$ErrFields['TraceInfo'] = Get-ObjectFieldValue -FieldName 'TraceInfo' -Object $ErrData -ErrorAction Stop
$ErrFields['CallStack'] = Get-ObjectFieldValue -FieldName 'CallStack' -Object $ErrData -ErrorAction Stop
}
}
If($ErrorRecord) {
$ErrFields['ErrorId'] = Get-ObjectFieldValue -FieldName 'FullyQualifiedErrorId' -Object $ErrorRecord -ErrorAction Stop
$CategoryInfo = Get-ObjectFieldValue -FieldName 'CategoryInfo' -Object $ErrorRecord
If($CategoryInfo) {
$ErrFields['Category'] = Get-ObjectFieldValue -FieldName 'Category' -Object $CategoryInfo -ErrorAction Stop
$ErrFields['Reason'] = Get-ObjectFieldValue -FieldName 'Reason' -Object $CategoryInfo -ErrorAction Stop
$ErrFields['TargetName'] = Get-ObjectFieldValue -FieldName 'TargetName' -Object $CategoryInfo -ErrorAction Stop
$ErrFields['TargetType'] = Get-ObjectFieldValue -FieldName 'TargetType' -Object $CategoryInfo -ErrorAction Stop
}
$ErrFields['ErrDetails'] = Get-ObjectFieldValue -FieldName 'ErrorDetails' -Object $ErrorRecord -ErrorAction Stop
$InvocationInfo = Get-ObjectFieldValue -FieldName 'InvocationInfo' -Object $ErrorRecord -ErrorAction Stop
If($InvocationInfo) {
$ErrFields['ErrLine'] = ([string]$(Get-ObjectFieldValue -FieldName 'Line' -Object $InvocationInfo -ErrorAction Stop)).TrimEnd("`r","`n"," ")
$ErrFields['LineNum'] = Get-ObjectFieldValue -FieldName 'ScriptLineNumber' -Object $InvocationInfo -ErrorAction Stop
$ErrFields['Position'] = Get-ObjectFieldValue -FieldName 'OffsetInLine' -Object $InvocationInfo -ErrorAction Stop
$FuncName = Get-ObjectFieldValue -FieldName 'MyCommand' -Object $InvocationInfo -ErrorAction Stop
$CallName = Get-ObjectFieldValue -FieldName 'InvocationName' -Object $InvocationInfo -ErrorAction Stop
$ErrFields['FuncName'] = $FuncName
$ErrFields['CallName'] = $CallName
$PosMsg = Get-ObjectFieldValue -FieldName 'PositionMessage' -Object $InvocationInfo -ErrorAction Stop
$PosMsg = Format-ErrorPositionMessage $PosMsg -ErrorAction Stop
$ErrFields['ErrPosition'] = $PosMsg
}
$StackTrace = Get-ObjectFieldValue -FieldName 'ScriptStackTrace' -Object $ErrorRecord -ErrorAction Stop
If($StackTrace) {
[Hashtable[]]$ErrorTraces = [Hashtable[]](Get-ErrorStackTrace $StackTrace -ErrorAction Stop)
$ErrFields['ErrTraces'] = $ErrorTraces
If($null -ne $ErrorTraces -And $ErrorTraces.Count -gt 0) {
If(-Not $FuncName) { $ErrFields['FuncName'] = $ErrorTraces[-1].StackFuncName }
}
$ErrorTraceMsg = $(Foreach ($ErrorTrace in $ErrorTraces) {
"$($ErrorTrace['StackFuncName']){... at Line:$($ErrorTrace.LineNum) "
}) -join "-> "
$ErrFields['ErrTraceMsg'] = $ErrorTraceMsg
}
}
return [Hashtable]$ErrFields
}
<#
.SYNOPSIS
Title : Function Get-ObjectFieldValue
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER Object
(Mandatory) Specifies ...
Expected type: [Object]
.PARAMETER FieldName
(Mandatory) Specifies ...
Expected type: [String]
.INPUTS
None
.OUTPUTS
$null - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Get-ObjectFieldValue -Object $Object -FieldName $FieldName
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Get-ObjectFieldValue {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[Object]$Object,
[Parameter(Mandatory)]
[string]$FieldName
)
If ($null -eq $Object) { return $null }
If(@(Get-Member -Input $Object -Member Properties -ErrorAction Stop | Select -Expand Name) -contains $FieldName) {
return $Object.$FieldName
} ElseIf (@(Get-Member -Input $Object -Member Properties -ErrorAction Stop | Select -Expand Name) -contains 'Keys') {
return $Object[$FieldName]
}
return $null
}
<#
.SYNOPSIS
Title : Function Traverse-ErrorRecord
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorRecord
(Mandatory) Specifies ...
Expected type: [ErrorRecord]
.PARAMETER NestingType
(Mandatory) Specifies ...
Expected type: [String]
Allowed Values: Exception, InnerException
Default Value: 'Exception'
.INPUTS
None
.OUTPUTS
$NestedRecord - returned when ...
$innerRecord - returned when ...
$null - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Traverse-ErrorRecord -ErrorRecord $ErrorRecord -NestingType $NestingType
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Traverse-ErrorRecord {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[System.Management.Automation.ErrorRecord]$ErrorRecord,
[Parameter(Mandatory)]
[ValidateSet('Exception','InnerException')]
[string]$NestingType = 'Exception'
)
If ($NestingType -eq 'Exception') {
If($null -ne $ErrorRecord) {
$ExceptionObject = Get-ObjectFieldValue -FieldName 'Exception' -Object $ErrorRecord -ErrorAction Stop
If($null -ne $ExceptionObject) {
$NestedRecord = Get-ObjectFieldValue -FieldName 'ErrorRecord' -Object $ExceptionObject -ErrorAction Stop
If($NestedRecord) {
return $NestedRecord
}
}
}
} ElseIf ($NestingType -eq 'InnerException') {
If($null -ne $ErrorRecord) {
$exceptionObject = Get-ObjectFieldValue -FieldName 'Exception' -Object $ErrorRecord -ErrorAction Stop
If($null -ne $exceptionObject) {
$innerExceptionObject = Get-ObjectFieldValue -FieldName 'InnerException' -Object $ErrorRecord.Exception -ErrorAction Stop
If($null -ne $innerExceptionObject) {
$innerRecord = Get-ObjectFieldValue -FieldName 'ErrorRecord' -Object $innerExceptionObject -ErrorAction Stop
If($null -ne $innerRecord) {
return $innerRecord
}
}
}
}
}
return $null
}
<#
.SYNOPSIS
Title : Function Build-TraceErrorDetails
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorRecord
(Mandatory) Specifies ...
Expected type: [ErrorRecord]
.INPUTS
None
.OUTPUTS
$Errors - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Build-TraceErrorDetails -ErrorRecord $ErrorRecord
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Build-TraceErrorDetails {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
[Hashtable[]]$Errors = @()
$currentRecord = $ErrorRecord
[byte]$MaxDepth = 5
[byte]$index = 0
While ($currentRecord) {
$currentError = @{}
$exceptionObject = Get-ObjectFieldValue -Object $currentRecord -FieldName 'Exception' -ErrorAction Stop
If ($exceptionObject) {
$currentError = $(Parse-ErrorDetails -ErrorRecord $currentRecord -Exception $exceptionObject -ErrorAction Stop)
} Else {
break
}
$innerErrors = @()
$innerException = Get-ObjectFieldValue -Object $exceptionObject -FieldName 'InnerException' -ErrorAction Stop
If ($innerException) {
$innerRecord = Traverse-ErrorRecord -ErrorRecord $currentRecord -NestingType 'InnerException' -ErrorAction Stop
If ($innerRecord) { # If there is embedded ErrorRecord inside InnerException, then proceed to parse information from it
# Nesting structure: $currentRecord.Exception.InnerException.ErrorRecord
$exceptionObject = Get-ObjectFieldValue -Object $innerRecord -FieldName 'Exception' -ErrorAction Stop
If ($exceptionObject) {
$innerIndex = 0
While ($innerRecord) {
$innerError = Parse-ErrorDetails -ErrorRecord $innerRecord -Exception $exceptionObject -ErrorAction Stop
$innerErrors += $innerError
$innerIndex++
If ($innerIndex -gt $MaxDepth) { break }
$innerRecord = Traverse-ErrorRecord -ErrorRecord $innerRecord -NestingType 'InnerException' -ErrorAction Stop
}
}
} Else { # Else - proceed to parse information just from InnerException
$innerError = Parse-ErrorDetails -Exception $innerException -ErrorAction Stop
$innerErrors += $innerError
}
}
$currentError['innerErrors'] = $innerErrors
$Errors += $currentError
$index++
If ($index -gt $MaxDepth) { break }
$currentRecord = $(Traverse-ErrorRecord -ErrorRecord $currentRecord -NestingType Exception -ErrorAction Stop)
}
return $Errors
}
<#
.SYNOPSIS
Title : Function Format-TraceErrorMessage
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorDetail
(Mandatory) Specifies ...
Expected type: [Hashtable]
.INPUTS
None
.OUTPUTS
$errorMessage - returned when ...
.EXAMPLE
# Usage Case ... Example Description :
PS > Format-TraceErrorMessage -ErrorDetail $ErrorDetail
.LINK
https://github.com/jondamvi/PSV.DebugTraceTools
#>
Function Format-TraceErrorMessage {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[Hashtable]$ErrorDetail
)
[Hashtable]$item = $ErrorDetail
[string[]]$errorMessage = [string[]]@()
[string]$ErrorDelimiterLine = [string]$('-' * 80)
If($item.Message) { $errorMessage += "$($item.Message)" }
$errorMessage += $ErrorDelimiterLine
$errorMessage += '[TRACE Error Details]'
If($item.Reason) { $errorMessage += "Reason: $($item.Reason)" }
If($item.Category -And $item.Category -ne 'NotSpecified') {
$errorMessage += "Category: $($item.Category)"
}
If($item.ErrorId) { $errorMessage += "Error ID: $($item.ErrorId)" }
If($item.ErrCodeD) { $errorMessage += "Error Code DEC: $($item.ErrCodeD)" }
If($item.ErrCodeH) { $errorMessage += "Error Code HEX: $($item.ErrCodeH)" }
If($item.Win32ErrMsg) {
$errorMessage += "Win32 Error Message: $($item.Win32ErrMsg)"
}
$AliasName = $(If($item.CallName -And $item.CallName -ne $item.FuncName) { $item.CallName })
$CalledFuncName = $(If(-Not $AliasName) { $($item.FuncName) } Else { "#$AliasName->[$CalledFuncName]" })
If($CalledFuncName) { $errorMessage += "Occurred at: $CalledFuncName" }
If($AliasName) {
$errorMessage += "Invoked Alias Name: $($item.CallName)"
}
If($item.ThrowManual) { $errorMessage += "Thrown Manually: $($item.ThrowManual)" }
If($item.ErrTraceMsg) { $errorMessage += "Error Trace: $($item.ErrTraceMsg)" }
If($item.ErrDetails) { $errorMessage += "Error Details: $($item.ErrDetails)" }
If($item.ErrLine) { $errorMessage += "Error Line: $($item.ErrLine)" }
If($item.LineNum) { $errorMessage += "Line Number: $($item.LineNum)" }
If($item.Position) { $errorMessage += "Char Offset: $($item.Position)" }
If($item.ErrPosition) { $errorMessage += "Error Position: $($item.ErrPosition)" }
If($item.TargetName) { $errorMessage += "Target Name: $($item.TargetName)" }
If($item.TargetType) { $errorMessage += "Target Type: $($item.TargetType)" }
If($item.ThrowManual) {
$errorMessage += $ErrorDelimiterLine
$errorMessage += "[TRACE Variables]: $($item['TraceInfo'])"
$errorMessage += $ErrorDelimiterLine
$errorMessage += "[TRACE CallStack]: $($item['CallStack'])"
$errorMessage += $ErrorDelimiterLine
}
return [string[]]$errorMessage
}
<#
.SYNOPSIS
Title : Function Build-TraceErrorMessage
Author : Jon Damvi
Version : 1.0.0
Date : 01.06.2025
License : MIT (LICENSE)
Release Notes:
v1.0.0 (01.06.2025) - initial release (by Jon Damvi).
.DESCRIPTION
[Description to be added]
.PARAMETER ErrorDetails
(Mandatory) Specifies ...
Expected type: [Hashtable[]]
.INPUTS
None
.OUTPUTS
$errorMessages - returned when ...
.EXAMPLE
# Usage Case ... Example Description :