-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-StatUpdateDiag.ps1
More file actions
1832 lines (1588 loc) · 84 KB
/
Copy pathInvoke-StatUpdateDiag.ps1
File metadata and controls
1832 lines (1588 loc) · 84 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
Multi-server diagnostic analysis for sp_StatUpdate using CommandLog data.
.DESCRIPTION
Orchestrates sp_StatUpdate_Diag across one or more SQL Servers in parallel,
merges results, detects cross-server patterns, and generates a consolidated
Markdown or HTML report with severity-categorized recommendations.
When -Obfuscate is specified, produces three output files:
- _SAFE_TO_SHARE: obfuscated data safe for vendors/consultants
- _CONFIDENTIAL: real names for internal use only
- _CONFIDENTIAL_DECODE.sql: T-SQL script to decode obfuscated tokens
Prerequisites:
- PowerShell 7+
- sp_StatUpdate_Diag procedure deployed on target servers
.PARAMETER Servers
Array of SQL Server instance names to analyze.
.PARAMETER CommandLogDatabase
Database containing dbo.CommandLog table. Defaults to 'master'.
.PARAMETER OutputPath
Directory for report output. Defaults to current directory.
.PARAMETER OutputFormat
Narrative report format: Markdown, HTML, or JSON. Defaults to Markdown.
A per-result-set CSV export is written on every run regardless of this
setting: one CSV per result set, unioned across the whole fleet with a
leading Server column, in a <basename>_csv subfolder. That is the shape
you want for Excel/Power BI. Suppress it with -NoCsv.
-OutputFormat CSV writes only that export and skips the narrative report.
.PARAMETER NoCsv
Suppress the per-result-set CSV export. Ignored when -OutputFormat is CSV
(that would leave the run with no output at all).
.PARAMETER DaysBack
Number of days of history to analyze. Defaults to 30.
.PARAMETER MaxParallel
Maximum parallel threads. Defaults to 10.
.PARAMETER Obfuscate
When specified, produces dual output: obfuscated (safe to share) and
confidential (real names). Also generates a decode SQL script.
.PARAMETER ObfuscationSeed
Salt for the obfuscation hashes. MANDATORY with -Obfuscate.
Unseeded, the tokens are a bare MD5/SHA of the real name, so a recipient
can recover 'dbo', 'Orders', 'Production', and your instance names from a
short dictionary in seconds -- the _SAFE_TO_SHARE file would not be safe
to share. Seeded, the same name maps to the same token across runs and
across the fleet (so reports stay comparable over time) but is opaque to
anyone without the seed. Treat the seed as a secret; keep it stable.
The seed travels to each instance as a literal in the EXECUTE batch, so it
is visible in sys.dm_exec_sql_text, Query Store and any SQL audit on those
servers. That is fine against the threat this defends -- the report
recipient has no DMV access, and anyone who does already has the real
names -- but do not reuse a password as the seed.
.PARAMETER ObfuscationMapTable
Persist the obfuscation map to this table on each server (auto-created if missing).
The map stays on prod for decoding. Requires -Obfuscate.
.PARAMETER SkipHistory
Pass @SkipHistory = 1, so sp_StatUpdate_Diag neither creates nor writes
dbo.StatUpdateDiagHistory on the target instances. Use when you do not want
the diagnostic to leave a permanent table behind on every box in the fleet.
Note this also disables the "trend vs prior assessment" line in the dashboard.
.PARAMETER TimeLimitExhaustionPct
Percentage of runs that must hit TIME_LIMIT before C3 fires. Defaults to 80.
.PARAMETER GradeOverrides
Passed through to @GradeOverrides, e.g. 'RELIABILITY=A, SPEED=IGNORE'.
Applies to every server in the fleet run.
.PARAMETER GradeWeights
Passed through to @GradeWeights, e.g. 'COMPLETION=40, WORKLOAD=40'.
Applies to every server in the fleet run.
.PARAMETER NoServerDetail
Omit the per-server "Server Details" sections from the narrative report and
keep only the Fleet Scoreboard and grouped findings. Past roughly 25
instances the detail sections are hundreds of tables nobody reads; the CSV
export carries the same data in a form you can actually query.
.PARAMETER ExpertMode
0 = management view (dashboard + recommendations only), 1 = DBA deep-dive (all 13 RS).
Defaults to 0.
.PARAMETER LongRunningMinutes
Threshold for long-running stat detection. Defaults to 10.
.PARAMETER FailureThreshold
Number of failures before triggering C2 CRITICAL. Defaults to 3.
.PARAMETER ThroughputWindowDays
Window for throughput trend analysis (C4). Defaults to 7.
.PARAMETER TopN
Limit for detail result sets. Defaults to 20.
.PARAMETER EfficacyDaysBack
Broad trending window for QS efficacy analysis (RS 9). Defaults to @DaysBack.
.PARAMETER EfficacyDetailDays
Close-up run-over-run window for QS efficacy detail (RS 10). Defaults to 14.
.PARAMETER TrustServerCertificate
Trust the SQL Server certificate without validation. Defaults to $true.
Set to $false when connecting to servers with properly configured TLS certificates.
.PARAMETER Credential
Optional PSCredential for SQL authentication. If not provided, uses Windows auth.
.PARAMETER ConnectTimeout
Seconds to wait for a connection to each server. Defaults to 30.
.PARAMETER QueryTimeout
Seconds to wait for sp_StatUpdate_Diag to return. Defaults to 600.
Raise this for servers with deep CommandLog retention or a large -DaysBack.
.PARAMETER RetryCount
Additional attempts per server after a failure. Defaults to 1 (two tries total).
Set to 0 to fail fast.
.PARAMETER PassThru
Emit a result object (per-server status, recommendations, output file paths)
to the pipeline so the run can be consumed by automation.
.EXAMPLE
# Single server, Windows auth
.\Invoke-StatUpdateDiag.ps1 -Servers @('PROD-SQL01')
.EXAMPLE
# Multi-server, obfuscated for sharing. -ObfuscationSeed is mandatory here.
.\Invoke-StatUpdateDiag.ps1 -Servers @('PROD-SQL01','PROD-SQL02') -Obfuscate -ObfuscationSeed 'acme-2026' -OutputFormat JSON
.EXAMPLE
# SQL auth, custom CommandLog location
$cred = Get-Credential
.\Invoke-StatUpdateDiag.ps1 -Servers (Get-Content servers.txt) -Credential $cred -CommandLogDatabase 'DBATools'
.EXAMPLE
# Fleet run (15-75 instances), capturing the result object for automation.
# Note the call operator (&) -- do NOT dot-source (see .NOTES).
$splat = @{
Servers = Get-Content .\instances.txt
CommandLogDatabase = 'DBATools'
Obfuscate = $true
ObfuscationSeed = 'fleet-2026-Q3' # keep this constant across runs
OutputPath = 'D:\#DBA\reports'
Credential = $cred
MaxParallel = 16
NoServerDetail = $true # scoreboard + findings; detail lives in the CSVs
SkipHistory = $true # leave no permanent table on prod
PassThru = $true
}
$run = & .\Invoke-StatUpdateDiag.ps1 @splat
$run.Failures | Format-Table
$run.Files
.EXAMPLE
# Fleet data straight into Excel/Power BI, no narrative report
& .\Invoke-StatUpdateDiag.ps1 -Servers $instances -OutputFormat CSV -ExpertMode 1 -OutputPath 'D:\#DBA\csv'
# -> D:\#DBA\csv\sp_StatUpdate_Diag_<timestamp>_csv\{Dashboard,RunDetail,TopTables,...}.csv
.NOTES
Requires: PowerShell 7+ (uses ADO.NET directly, no SqlServer module needed)
Invoke with the call operator (&) or by path -- do NOT dot-source it.
Dot-sourcing leaks every script variable into the caller's session and
leaves $ErrorActionPreference = 'Stop' behind.
See also: sp_StatUpdate_Diag.sql (the T-SQL diagnostic procedure)
#>
[CmdletBinding()]
param(
# AllowEmptyString: a mandatory [string[]] rejects empty elements in the
# binder, so -Servers (Get-Content servers.txt) died on a trailing blank
# line with "Cannot bind argument ... empty string" and no hint as to which
# entry. The cleanup below strips blanks and says what it dropped instead.
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string[]]$Servers,
[string]$CommandLogDatabase = "master",
[string]$OutputPath = ".",
[ValidateSet("Markdown", "HTML", "JSON", "CSV")]
[string]$OutputFormat = "Markdown",
[switch]$NoCsv,
[int]$DaysBack = 30,
[int]$MaxParallel = 10,
[switch]$Obfuscate,
[string]$ObfuscationSeed,
[string]$ObfuscationMapTable,
[int]$ExpertMode = 0,
[int]$LongRunningMinutes = 10,
[int]$FailureThreshold = 3,
[ValidateRange(1, 100)]
[int]$TimeLimitExhaustionPct = 80,
[int]$ThroughputWindowDays = 7,
[int]$TopN = 20,
[switch]$SkipHistory,
[string]$GradeOverrides,
[string]$GradeWeights,
[switch]$NoServerDetail,
[Nullable[int]]$EfficacyDaysBack,
[Nullable[int]]$EfficacyDetailDays,
[bool]$TrustServerCertificate = $true,
[PSCredential]$Credential,
[ValidateRange(5, 600)]
[int]$ConnectTimeout = 30,
[ValidateRange(30, 21600)]
[int]$QueryTimeout = 600,
[ValidateRange(0, 5)]
[int]$RetryCount = 1,
[switch]$PassThru
)
$ErrorActionPreference = "Stop"
# =============================================================================
# Prerequisites
# =============================================================================
if ($PSVersionTable.PSVersion.Major -lt 7) {
throw "This script requires PowerShell 7 or higher. Current version: $($PSVersionTable.PSVersion)"
}
if (-not (Test-Path -LiteralPath $OutputPath)) {
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}
# -LiteralPath: fleet report directories routinely contain characters PowerShell
# treats as wildcards (D:\#DBA\csv, paths with [brackets]).
$OutputPath = (Resolve-Path -LiteralPath $OutputPath).Path
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
# De-duplicate and trim the instance list. Fleet inventories arrive from CMS
# queries and text files, and a repeated instance would be queried twice and
# then silently collapse to one key in $allResults.
$rawServerCount = $Servers.Count
$Servers = @(
$Servers |
ForEach-Object { if ($null -ne $_) { $_.Trim() } } |
Where-Object { $_ } |
Sort-Object -Unique
)
if ($Servers.Count -eq 0) {
throw "No usable instance names in -Servers (all entries were empty or whitespace)."
}
if ($Servers.Count -ne $rawServerCount) {
Write-Warning "-Servers reduced from $rawServerCount to $($Servers.Count) entries (blanks/duplicates removed)."
}
# Unseeded obfuscation is not obfuscation. Both hashing layers -- HASHBYTES('MD5')
# in the proc and SHA256 for the SRV_ tokens here -- reduce to a bare hash of the
# real name when the seed is empty, so anyone holding a _SAFE_TO_SHARE file can
# recover 'dbo', 'Orders', 'Production' and your instance names from a short
# dictionary. Refusing is the only honest option for a file named SAFE_TO_SHARE.
if ($Obfuscate -and [string]::IsNullOrWhiteSpace($ObfuscationSeed)) {
throw @"
-Obfuscate requires -ObfuscationSeed.
Without a seed the tokens are unsalted hashes of the real names and are
reversible by dictionary attack, so the _SAFE_TO_SHARE file would not be
safe to share. Pass a secret you keep constant across runs, e.g.:
-Obfuscate -ObfuscationSeed 'fleet-2026-Q3'
Keeping the seed stable is what makes two reports comparable over time;
changing it renumbers every token.
"@
}
if ($ObfuscationSeed -and -not $Obfuscate) {
Write-Warning "-ObfuscationSeed is ignored without -Obfuscate; this run will emit real names."
}
if ($ObfuscationMapTable -and -not $Obfuscate) {
Write-Warning "-ObfuscationMapTable is ignored without -Obfuscate; no map will be written."
}
if ($NoCsv -and $OutputFormat -eq "CSV") {
Write-Warning "-NoCsv ignored with -OutputFormat CSV (it would leave the run with no output)."
$NoCsv = $false
}
# In -Obfuscate mode the script issues two proc calls per server and both are
# pinned to ExpertMode=1: the confidential pass feeds cross-server analysis
# (which needs RS4) and the obfuscated pass must return the obfuscation map RS.
if ($Obfuscate -and $ExpertMode -ne 1) {
Write-Warning "-Obfuscate forces ExpertMode=1 on both proc calls; the -ExpertMode $ExpertMode you passed is ignored."
}
# Without RS4 there is no Version or TimeLimit data, so cross-server analysis
# cannot run. Say so up front rather than reporting zero findings.
$crossServerAnalysisEnabled = ($Obfuscate -or $ExpertMode -eq 1)
if (-not $crossServerAnalysisEnabled) {
Write-Warning "Cross-server analysis (version skew, parameter drift) needs -ExpertMode 1; it will be skipped."
}
Write-Host "===============================================================================" -ForegroundColor Cyan
Write-Host " sp_StatUpdate Diagnostic Analysis" -ForegroundColor Cyan
Write-Host "===============================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Servers: $($Servers.Count)"
Write-Host "CommandLog DB: $CommandLogDatabase"
Write-Host "Days back: $DaysBack"
Write-Host "Obfuscate: $Obfuscate$(if ($ObfuscationSeed) { ' (seeded)' })$(if ($Obfuscate) { ' (dual output)' })"
Write-Host "ExpertMode: $(if ($Obfuscate) { '1 (forced by -Obfuscate)' } else { $ExpertMode })"
Write-Host "Parallelism: $MaxParallel"
Write-Host "Timeouts: connect ${ConnectTimeout}s / query ${QueryTimeout}s"
Write-Host "Output: $OutputPath"
Write-Host "Format: $OutputFormat$(if (-not $NoCsv -and $OutputFormat -ne 'CSV') { ' + per-result-set CSV' })"
# o2md.40: prefer Microsoft.Data.SqlClient when resolvable, fall back to the
# legacy (but runtime-bundled) System.Data.SqlClient otherwise. The modern
# provider is a separate NuGet package, NOT part of the default PowerShell
# runtime -- a hard switch would break every machine without it installed.
# Assemblies are process-wide, so a type loaded here resolves inside the
# ForEach-Object -Parallel runspaces too.
$script:ModernSqlClient = $false
try { $null = [Microsoft.Data.SqlClient.SqlConnection]; $script:ModernSqlClient = $true }
catch {
try { Add-Type -AssemblyName 'Microsoft.Data.SqlClient' -ErrorAction Stop; $null = [Microsoft.Data.SqlClient.SqlConnection]; $script:ModernSqlClient = $true } catch { }
}
Write-Host "SQL client: $(if ($script:ModernSqlClient) { 'Microsoft.Data.SqlClient' } else { 'System.Data.SqlClient (legacy fallback -- install Microsoft.Data.SqlClient to modernize)' })"
Write-Host "Server detail: $(if ($NoServerDetail) { 'omitted (-NoServerDetail)' } else { 'included' })"
Write-Host "Diag history: $(if ($SkipHistory) { 'skipped (@SkipHistory = 1)' } else { 'written to dbo.StatUpdateDiagHistory on each instance' })"
Write-Host ""
# The per-server sections are ~10 tables each. Past a couple of dozen instances
# nobody reads them, and the CSV export carries the same rows in queryable form.
if (-not $NoServerDetail -and $OutputFormat -ne "CSV" -and $Servers.Count -gt 25) {
Write-Host " Hint: $($Servers.Count) instances will produce ~$($Servers.Count * 10) per-server tables in one file." -ForegroundColor DarkYellow
Write-Host " Consider -NoServerDetail and read the detail from the CSV export instead." -ForegroundColor DarkYellow
Write-Host ""
}
# =============================================================================
# Execute sp_StatUpdate_Diag on each server
# =============================================================================
$procParams = @{
DaysBack = $DaysBack
ObfuscationSeed = $ObfuscationSeed
ObfuscationMapTable = $ObfuscationMapTable
ExpertMode = $ExpertMode
LongRunningMinutes = $LongRunningMinutes
FailureThreshold = $FailureThreshold
TimeLimitExhaustionPct = $TimeLimitExhaustionPct
ThroughputWindowDays = $ThroughputWindowDays
TopN = $TopN
EfficacyDaysBack = $EfficacyDaysBack
EfficacyDetailDays = $EfficacyDetailDays
CommandLogDatabase = $CommandLogDatabase
SkipHistory = [int][bool]$SkipHistory
GradeOverrides = $GradeOverrides
GradeWeights = $GradeWeights
IsObfuscateMode = [bool]$Obfuscate
}
# Thread-safe collections for parallel execution
$allResults = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new()
$allErrors = [System.Collections.Concurrent.ConcurrentBag[PSObject]]::new()
$progress = [System.Collections.Concurrent.ConcurrentDictionary[string, string]]::new()
Write-Host "Querying $($Servers.Count) server(s)..." -ForegroundColor Yellow
Write-Host ""
$fleetSw = [System.Diagnostics.Stopwatch]::StartNew()
# Each instance reports as it lands. A fleet run is otherwise silent for minutes,
# which is indistinguishable from a hang. The downstream ForEach-Object must stay
# attached to the pipeline -- assigning the parallel output to a variable first
# would buffer everything until the last server finished.
$script:serverStatus = [System.Collections.Generic.List[PSObject]]::new()
$script:serversDone = 0
$serverTotal = $Servers.Count
$Servers | ForEach-Object -ThrottleLimit $MaxParallel -Parallel {
$server = $_
$paramsLocal = $using:procParams
$resultsLocal = $using:allResults
$errorsLocal = $using:allErrors
$progressLocal = $using:progress
$credLocal = $using:Credential
$dbLocal = $using:CommandLogDatabase
$trustCert = $using:TrustServerCertificate
$connTimeout = $using:ConnectTimeout
$queryTimeout = $using:QueryTimeout
$retries = $using:RetryCount
$modernSql = $using:ModernSqlClient
$progressLocal[$server] = "Running"
$sw = [System.Diagnostics.Stopwatch]::StartNew()
# Maps DataSet tables to named result sets by unique column signatures.
# Defined inside the parallel block because scriptblocks can't cross the $using: boundary.
function Map-ResultSets {
param([System.Data.DataSet]$DataSet)
$map = @{}
foreach ($table in $DataSet.Tables) {
$cols = $table.Columns | ForEach-Object { $_.ColumnName }
if ($cols -contains "Grade" -and $cols -contains "Score" -and $cols -contains "Headline") { $map["Dashboard"] = $table }
elseif ($cols -contains "Finding" -and $cols -contains "Recommendation" -and $cols -contains "Severity") { $map["Recommendations"] = $table }
elseif ($cols -contains "TotalRuns") { $map["RunHealth"] = $table }
elseif ($cols -contains "RunLabel" -and $cols -contains "StopReason" -and $cols -contains "IsKilled") { $map["RunDetail"] = $table }
elseif ($cols -contains "TotalDurationSec") { $map["TopTables"] = $table }
# o2md.39: this heuristic checked for a column named "FailureCount", but RS6's
# actual column (sp_StatUpdate_Diag.sql "RESULT SET 6: FAILING STATISTICS") is
# "FailCount" -- the mismatch meant this branch never matched and FailingStats
# silently fell through to the else/warning branch on every run. Found live by
# that new warning while testing it.
elseif ($cols -contains "FailCount") { $map["FailingStats"] = $table }
elseif ($cols -contains "AvgDurationSec" -and -not ($cols -contains "FailCount")) { $map["LongRunning"] = $table }
elseif ($cols -contains "TieredThresholds") { $map["ParamHistory"] = $table }
elseif ($cols -contains "OriginalName" -and $cols -contains "ObfuscatedName") { $map["ObfuscationMap"] = $table }
elseif ($cols -contains "WeekLabel" -and $cols -contains "TrendDirection") { $map["EfficacyTrend"] = $table }
elseif ($cols -contains "DeltaVsPrior") { $map["EfficacyDetail"] = $table }
elseif ($cols -contains "ProcessingPosition" -and $cols -contains "WorkloadRank") { $map["HighCpuPositions"] = $table }
elseif ($cols -contains "CpuTrend" -and $cols -contains "CpuChangePct") { $map["QSCorrelation"] = $table }
else {
# o2md.39: previously silent -- a future Diag column change would
# misroute or drop a result set with no signal, indistinguishable
# from o2md.30 (collected but never rendered). PS7's -Parallel
# streams Warning output back to the caller, so this surfaces even
# though Map-ResultSets runs inside a parallel runspace per server.
Write-Warning "[$server] Map-ResultSets: table with columns ($($cols -join ', ')) matched no known signature -- this result set will be dropped from the report."
}
}
return $map
}
try {
# Connection string via the builder, not string concatenation: instance
# and database names are escaped correctly, and a password containing
# ; " or = can neither break the string nor inject a keyword.
# o2md.40: type literals resolve at runtime, so the modern branch is
# only evaluated when the assembly is confirmed loadable.
$csb = if ($modernSql) { [Microsoft.Data.SqlClient.SqlConnectionStringBuilder]::new() }
else { [System.Data.SqlClient.SqlConnectionStringBuilder]::new() }
$csb['Data Source'] = $server
$csb['Initial Catalog'] = $dbLocal
$csb['TrustServerCertificate'] = $trustCert
$csb['Connect Timeout'] = $connTimeout
# Identifies the session in sp_whoisactive / dm_exec_sessions on prod.
$csb['Application Name'] = 'Invoke-StatUpdateDiag'
$sqlCredential = $null
if ($credLocal) {
# SqlCredential carries the password as a read-only SecureString
# instead of materializing it in the connection string.
$securePw = $credLocal.Password.Copy()
$securePw.MakeReadOnly()
$sqlCredential = if ($modernSql) { [Microsoft.Data.SqlClient.SqlCredential]::new($credLocal.UserName, $securePw) }
else { [System.Data.SqlClient.SqlCredential]::new($credLocal.UserName, $securePw) }
}
else {
$csb['Integrated Security'] = $true
}
$connStr = $csb.ConnectionString
# Helper: build EXEC statement for sp_StatUpdate_Diag.
# Every string value goes through ConvertTo-SqlLiteral. These are all
# operator-supplied rather than attacker-supplied, but an -ObfuscationSeed
# or a database name containing an apostrophe would otherwise produce a
# syntactically broken batch and fail the whole instance for no reason.
function ConvertTo-SqlLiteral {
param([string]$Value)
return "N'" + $Value.Replace("'", "''") + "'"
}
function Build-ExecStatement {
param([int]$Obfuscate, [int]$ExpertMode, [hashtable]$Params)
$paramList = @(
"@DaysBack = $($Params.DaysBack)",
"@Obfuscate = $Obfuscate",
"@ExpertMode = $ExpertMode",
"@LongRunningMinutes = $($Params.LongRunningMinutes)",
"@FailureThreshold = $($Params.FailureThreshold)",
"@TimeLimitExhaustionPct = $($Params.TimeLimitExhaustionPct)",
"@ThroughputWindowDays = $($Params.ThroughputWindowDays)",
"@TopN = $($Params.TopN)",
"@SkipHistory = $($Params.SkipHistory)"
)
if ($Params.ObfuscationSeed -and $Obfuscate -eq 1) {
$paramList += "@ObfuscationSeed = $(ConvertTo-SqlLiteral $Params.ObfuscationSeed)"
}
if ($Params.ObfuscationMapTable -and $Obfuscate -eq 1) {
$paramList += "@ObfuscationMapTable = $(ConvertTo-SqlLiteral $Params.ObfuscationMapTable)"
}
if ($null -ne $Params.EfficacyDaysBack) {
$paramList += "@EfficacyDaysBack = $($Params.EfficacyDaysBack)"
}
if ($null -ne $Params.EfficacyDetailDays) {
$paramList += "@EfficacyDetailDays = $($Params.EfficacyDetailDays)"
}
if ($Params.GradeOverrides) {
$paramList += "@GradeOverrides = $(ConvertTo-SqlLiteral $Params.GradeOverrides)"
}
if ($Params.GradeWeights) {
$paramList += "@GradeWeights = $(ConvertTo-SqlLiteral $Params.GradeWeights)"
}
# Always passed, never inferred. The old code only sent this when it
# differed from the connection's Initial Catalog -- which, since both
# come from -CommandLogDatabase, was never. The proc then fell back to
# DB_NAME() and happened to be right, but only because the connection
# was pointed at the CommandLog database and sp_-prefixed procs resolve
# out of master. Stating it explicitly removes that coincidence.
if ($Params.CommandLogDatabase) {
$paramList += "@CommandLogDatabase = $(ConvertTo-SqlLiteral $Params.CommandLogDatabase)"
}
return "EXECUTE dbo.sp_StatUpdate_Diag $($paramList -join ', ');"
}
# Helper: execute a query and return DataSet.
# Retries on failure -- across a large fleet, a handful of instances will
# always drop a login or hit a transient network blip, and losing a whole
# server's report to one flaky connect is not worth it.
function Invoke-DiagCall {
param([string]$ConnStr, [string]$Sql, [int]$Timeout, $SqlCredential, [int]$Attempts)
$lastError = $null
for ($attempt = 0; $attempt -le $Attempts; $attempt++) {
# o2md.40: $modernSql resolves from the enclosing scriptblock scope
$c = if ($modernSql) { New-Object Microsoft.Data.SqlClient.SqlConnection($ConnStr) }
else { New-Object System.Data.SqlClient.SqlConnection($ConnStr) }
if ($SqlCredential) { $c.Credential = $SqlCredential }
$cm = $c.CreateCommand()
$cm.CommandTimeout = $Timeout
$cm.CommandText = $Sql
$a = if ($modernSql) { New-Object Microsoft.Data.SqlClient.SqlDataAdapter($cm) }
else { New-Object System.Data.SqlClient.SqlDataAdapter($cm) }
$d = New-Object System.Data.DataSet
try {
$c.Open()
$a.Fill($d) | Out-Null
return $d
}
catch {
$lastError = $_
# A query timeout means the proc really is that slow on this
# instance; retrying just burns another $Timeout seconds.
if ($_.Exception.Message -match 'Execution Timeout Expired') { throw }
}
finally {
$c.Close()
$c.Dispose()
}
if ($attempt -lt $Attempts) { Start-Sleep -Seconds (3 * ($attempt + 1)) }
}
throw $lastError
}
if ($paramsLocal.IsObfuscateMode) {
# --- Two-call architecture for obfuscation mode ---
# Call 1: Unobfuscated (Confidential) — always ExpertMode=1 for full data
$sql1 = Build-ExecStatement -Obfuscate 0 -ExpertMode 1 -Params $paramsLocal
$ds1 = Invoke-DiagCall -ConnStr $connStr -Sql $sql1 -Timeout $queryTimeout -SqlCredential $sqlCredential -Attempts $retries
$confidentialMap = Map-ResultSets $ds1
# Call 2: Obfuscated (SafeToShare) — always ExpertMode=1 for map RS
$sql2 = Build-ExecStatement -Obfuscate 1 -ExpertMode 1 -Params $paramsLocal
$ds2 = Invoke-DiagCall -ConnStr $connStr -Sql $sql2 -Timeout $queryTimeout -SqlCredential $sqlCredential -Attempts $retries
$safeToShareMap = Map-ResultSets $ds2
$result = @{
# Cross-server analysis and report generation use Confidential data
Dashboard = $confidentialMap["Dashboard"]
Recommendations = $confidentialMap["Recommendations"]
RunHealth = $confidentialMap["RunHealth"]
RunDetail = $confidentialMap["RunDetail"]
TopTables = $confidentialMap["TopTables"]
FailingStats = $confidentialMap["FailingStats"]
LongRunning = $confidentialMap["LongRunning"]
ParamHistory = $confidentialMap["ParamHistory"]
EfficacyTrend = $confidentialMap["EfficacyTrend"]
EfficacyDetail = $confidentialMap["EfficacyDetail"]
HighCpuPositions = $confidentialMap["HighCpuPositions"]
QSCorrelation = $confidentialMap["QSCorrelation"]
# Obfuscation-specific data
ObfuscationMap = $safeToShareMap["ObfuscationMap"]
ConfidentialDS = $ds1
SafeToShareDS = $ds2
SafeToShareMap = $safeToShareMap
}
}
else {
# --- Single call (no obfuscation) ---
$sql = Build-ExecStatement -Obfuscate 0 -ExpertMode $paramsLocal.ExpertMode -Params $paramsLocal
$ds = Invoke-DiagCall -ConnStr $connStr -Sql $sql -Timeout $queryTimeout -SqlCredential $sqlCredential -Attempts $retries
$rsMap = Map-ResultSets $ds
$result = @{
Dashboard = $rsMap["Dashboard"]
Recommendations = $rsMap["Recommendations"]
RunHealth = $rsMap["RunHealth"]
RunDetail = $rsMap["RunDetail"]
TopTables = $rsMap["TopTables"]
FailingStats = $rsMap["FailingStats"]
LongRunning = $rsMap["LongRunning"]
ParamHistory = $rsMap["ParamHistory"]
EfficacyTrend = $rsMap["EfficacyTrend"]
EfficacyDetail = $rsMap["EfficacyDetail"]
HighCpuPositions = $rsMap["HighCpuPositions"]
QSCorrelation = $rsMap["QSCorrelation"]
ObfuscationMap = $null
ConfidentialDS = $null
SafeToShareDS = $null
SafeToShareMap = $null
}
}
$resultsLocal[$server] = $result
$progressLocal[$server] = "Complete"
$sw.Stop()
[PSCustomObject]@{ Server = $server; Status = "Complete"; Seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); Error = $null }
}
catch {
$progressLocal[$server] = "Failed"
$sw.Stop()
$errorsLocal.Add([PSCustomObject]@{
Server = $server
Error = $_.Exception.Message
Timestamp = Get-Date
})
[PSCustomObject]@{ Server = $server; Status = "Failed"; Seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1); Error = $_.Exception.Message }
}
} | ForEach-Object {
$script:serverStatus.Add($_)
$script:serversDone++
$pct = [int](100 * $script:serversDone / $serverTotal)
if ($_.Status -eq "Complete") {
Write-Host (" [{0,3}%] {1,-40} OK {2,7}s" -f $pct, $_.Server, $_.Seconds) -ForegroundColor Green
}
else {
Write-Host (" [{0,3}%] {1,-40} FAIL {2,7}s {3}" -f $pct, $_.Server, $_.Seconds, $_.Error) -ForegroundColor Red
}
}
$fleetSw.Stop()
$completed = @($progress.Values | Where-Object { $_ -eq "Complete" }).Count
$failed = @($progress.Values | Where-Object { $_ -eq "Failed" }).Count
Write-Host ""
Write-Host " Completed: $completed of $($Servers.Count) in $([math]::Round($fleetSw.Elapsed.TotalSeconds, 1))s" -ForegroundColor Green
if ($failed -gt 0) {
Write-Host " Failed: $failed" -ForegroundColor Red
}
Write-Host ""
if ($completed -eq 0) {
# throw, not exit: 'exit' would kill the caller's session if this script is
# dot-sourced, and returns no diagnostic detail to automation.
throw "No servers returned data ($failed failed). First error: $(@($allErrors)[0].Error)"
}
# Deterministic per-server token. [string]::GetHashCode() is randomized per
# process in .NET Core, so the previous implementation produced a different
# SRV_xxxx token for the same instance on every run -- unusable for comparing
# two SAFE_TO_SHARE reports over time. SHA256 over seed+name is stable across
# runs and machines, and unpredictable to anyone without the seed.
$script:displayNameCache = @{}
function Get-DisplayName {
param([string]$ServerName)
if (-not $Obfuscate) { return $ServerName }
if ($script:displayNameCache.ContainsKey($ServerName)) { return $script:displayNameCache[$ServerName] }
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$bytes = [System.Text.Encoding]::UTF8.GetBytes("$ObfuscationSeed|$($ServerName.ToUpperInvariant())")
$hash = [System.BitConverter]::ToString($sha.ComputeHash($bytes)).Replace("-", "")
}
finally { $sha.Dispose() }
$token = "SRV_" + $hash.Substring(0, 8)
$script:displayNameCache[$ServerName] = $token
return $token
}
# =============================================================================
# Cross-Server Analysis (always uses Confidential/real data)
# =============================================================================
Write-Host "Running cross-server analysis..." -ForegroundColor Yellow
$crossServerFindings = [System.Collections.Generic.List[PSObject]]::new()
# Reads a column from a DataRow without assuming the column exists. Indexing a
# DataRow by a missing column name throws, and with $ErrorActionPreference =
# 'Stop' that would abort the whole fleet report over one schema difference
# (an older sp_StatUpdate_Diag on a single instance).
function Get-CellValue {
param([System.Data.DataRow]$Row, [string]$Column)
if (-not $Row) { return $null }
if (-not $Row.Table.Columns.Contains($Column)) { return $null }
$val = $Row[$Column]
if ($null -eq $val -or $val -eq [DBNull]::Value) { return $null }
return $val
}
# Version skew detection
$versions = @{}
if ($crossServerAnalysisEnabled) {
foreach ($server in $allResults.Keys) {
$data = $allResults[$server]
if ($data.RunDetail -and $data.RunDetail.Rows.Count -gt 0) {
$ver = Get-CellValue -Row $data.RunDetail.Rows[0] -Column "Version"
if ($ver) { $versions[$server] = $ver.ToString() }
}
}
}
$distinctVersions = @($versions.Values | Sort-Object -Unique)
if ($distinctVersions.Count -gt 1) {
$versionDetail = ($versions.GetEnumerator() | ForEach-Object { "$(Get-DisplayName $_.Key): $($_.Value)" }) -join ", "
$crossServerFindings.Add([PSCustomObject]@{
Severity = "WARNING"
Category = "VERSION_SKEW"
Finding = "sp_StatUpdate version varies across $($versions.Count) servers ($($distinctVersions.Count) distinct versions)"
Evidence = $versionDetail
Recommendation = "Standardize sp_StatUpdate version across all servers to ensure consistent behavior."
})
}
# Parameter inconsistency detection
$timeLimits = @{}
if ($crossServerAnalysisEnabled) {
foreach ($server in $allResults.Keys) {
$data = $allResults[$server]
if ($data.RunDetail -and $data.RunDetail.Rows.Count -gt 0) {
$tl = Get-CellValue -Row $data.RunDetail.Rows[0] -Column "TimeLimit"
if ($null -ne $tl) { $timeLimits[$server] = [int]$tl }
}
}
}
$distinctTimeLimits = @($timeLimits.Values | Sort-Object -Unique)
if ($distinctTimeLimits.Count -gt 1) {
$tlDetail = ($timeLimits.GetEnumerator() | ForEach-Object { "$(Get-DisplayName $_.Key): $($_.Value)s" }) -join ", "
$crossServerFindings.Add([PSCustomObject]@{
Severity = "INFO"
Category = "PARAM_INCONSISTENCY"
Finding = "TimeLimit varies across servers ($($distinctTimeLimits -join ', ') seconds)"
Evidence = $tlDetail
Recommendation = "Review whether different time limits are intentional (different maintenance windows) or accidental."
})
}
if ($crossServerAnalysisEnabled) {
Write-Host " Cross-server findings: $($crossServerFindings.Count)" -ForegroundColor $(if ($crossServerFindings.Count -gt 0) { "Yellow" } else { "Green" })
}
else {
Write-Host " Cross-server findings: skipped (requires -ExpertMode 1 or -Obfuscate)" -ForegroundColor DarkGray
}
Write-Host ""
# =============================================================================
# Aggregate Recommendations
# =============================================================================
Write-Host "Aggregating recommendations..." -ForegroundColor Yellow
$allRecommendations = [System.Collections.Generic.List[PSObject]]::new()
foreach ($server in $allResults.Keys) {
$data = $allResults[$server]
if ($data.Recommendations -and $data.Recommendations.Rows.Count -gt 0) {
foreach ($row in $data.Recommendations.Rows) {
$allRecommendations.Add([PSCustomObject]@{
Server = (Get-DisplayName $server)
Severity = $row["Severity"].ToString()
Category = $row["Category"].ToString()
Finding = $row["Finding"].ToString()
Evidence = if ($row["Evidence"] -ne [DBNull]::Value) { $row["Evidence"].ToString() } else { "" }
Recommendation = if ($row["Recommendation"] -ne [DBNull]::Value) { $row["Recommendation"].ToString() } else { "" }
ExampleCall = if ($row["ExampleCall"] -ne [DBNull]::Value) { $row["ExampleCall"].ToString() } else { "" }
})
}
}
}
# Add cross-server findings
foreach ($finding in $crossServerFindings) {
$allRecommendations.Add([PSCustomObject]@{
Server = "CROSS-SERVER"
Severity = $finding.Severity
Category = $finding.Category
Finding = $finding.Finding
Evidence = $finding.Evidence
Recommendation = $finding.Recommendation
ExampleCall = ""
})
}
$criticalCount = ($allRecommendations | Where-Object { $_.Severity -eq "CRITICAL" }).Count
$warningCount = ($allRecommendations | Where-Object { $_.Severity -eq "WARNING" }).Count
$infoCount = ($allRecommendations | Where-Object { $_.Severity -eq "INFO" }).Count
Write-Host " CRITICAL: $criticalCount" -ForegroundColor $(if ($criticalCount -gt 0) { "Red" } else { "Green" })
Write-Host " WARNING: $warningCount" -ForegroundColor $(if ($warningCount -gt 0) { "Yellow" } else { "Green" })
Write-Host " INFO: $infoCount" -ForegroundColor Cyan
Write-Host ""
# =============================================================================
# Report Generation
# =============================================================================
Write-Host "Generating $OutputFormat report..." -ForegroundColor Yellow
function ConvertTo-MarkdownTable {
param([System.Data.DataTable]$Table, [int]$MaxRows = 50)
if (-not $Table -or $Table.Rows.Count -eq 0) { return "*No data*`n" }
$cols = $Table.Columns | ForEach-Object { $_.ColumnName }
$header = "| " + ($cols -join " | ") + " |"
$separator = "| " + (($cols | ForEach-Object { "---" }) -join " | ") + " |"
$rows = @($header, $separator)
$count = 0
foreach ($row in $Table.Rows) {
if ($count -ge $MaxRows) {
$rows += "| *... $($Table.Rows.Count - $MaxRows) more rows* |" + (" |" * ($cols.Count - 1))
break
}
$values = $cols | ForEach-Object {
$val = $row[$_]
if ($val -eq [DBNull]::Value) { "" }
else { $val.ToString().Replace("|", "\|").Replace("`n", " ") }
}
$rows += "| " + ($values -join " | ") + " |"
$count++
}
return ($rows -join "`n") + "`n"
}
# o2md.51: severity + grade visual markers (theme-agnostic -- render in both
# GitHub light/dark modes; a .md cannot force its own theme, the viewer decides).
function Get-SeverityEmoji {
param([string]$Severity)
switch ($Severity) {
"CRITICAL" { "`u{1F534}" } # red circle
"WARNING" { "`u{1F7E0}" } # orange circle
"INFO" { "`u{1F535}" } # blue circle
default { "`u{26AA}" } # white circle
}
}
function Get-GradeBadge {
param([string]$Grade)
switch -Regex ($Grade) {
"^[AB]" { "`u{1F7E2} $Grade" } # green
"^C" { "`u{1F7E1} $Grade" } # yellow
"^D" { "`u{1F7E0} $Grade" } # orange
"^F" { "`u{1F534} $Grade" } # red
default { if ($Grade) { $Grade } else { "?" } }
}
}
function Build-MarkdownReport {
param(
[hashtable]$AllResults,
[System.Collections.Generic.List[PSObject]]$AllRecommendations,
[bool]$IsObfuscated,
[PSObject[]]$ConnectionErrors = @()
)
$report = [System.Text.StringBuilder]::new()
# Counts MUST come from the recommendation list actually being rendered.
# (Previously these read script-scope $criticalCount/$warningCount/$infoCount,
# which are computed from the non-obfuscated pass, so the SAFE_TO_SHARE
# report's summary disagreed with its own body.)
$critCount = @($AllRecommendations | Where-Object { $_.Severity -eq "CRITICAL" }).Count
$warnCount = @($AllRecommendations | Where-Object { $_.Severity -eq "WARNING" }).Count
$nfoCount = @($AllRecommendations | Where-Object { $_.Severity -eq "INFO" }).Count
[void]$report.AppendLine("# sp_StatUpdate Diagnostic Report")
[void]$report.AppendLine("")
[void]$report.AppendLine("Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')")
[void]$report.AppendLine("Servers analyzed: $($Servers.Count) (completed: $completed, failed: $failed)")
[void]$report.AppendLine("Analysis window: $DaysBack days")
if ($IsObfuscated) { [void]$report.AppendLine("**Mode: OBFUSCATED** (names hashed for safe sharing)") }
[void]$report.AppendLine("")
# Executive Summary
[void]$report.AppendLine("## Executive Summary")
[void]$report.AppendLine("")
[void]$report.AppendLine("| Severity | Count |")
[void]$report.AppendLine("| --- | --- |")
[void]$report.AppendLine("| $(Get-SeverityEmoji 'CRITICAL') CRITICAL | $critCount |")
[void]$report.AppendLine("| $(Get-SeverityEmoji 'WARNING') WARNING | $warnCount |")
[void]$report.AppendLine("| $(Get-SeverityEmoji 'INFO') INFO | $nfoCount |")
[void]$report.AppendLine("")
# o2md.51: top-issues callout -- GitHub-flavored alert block ([!CAUTION] /
# [!WARNING]); renders as a plain blockquote on renderers without alerts.
$calloutSeverity = if ($critCount -gt 0) { "CRITICAL" } elseif ($warnCount -gt 0) { "WARNING" } else { $null }
if ($calloutSeverity) {
$alertKind = if ($calloutSeverity -eq "CRITICAL") { "CAUTION" } else { "WARNING" }
$topGroups = @($AllRecommendations |
Where-Object { $_.Severity -eq $calloutSeverity } |
Group-Object -Property { "$($_.Category)`u{241F}$($_.Finding)" } |
Sort-Object -Property @{ Expression = { $_.Count }; Descending = $true } |
Select-Object -First 3)
[void]$report.AppendLine("> [!$alertKind]")
[void]$report.AppendLine("> **Top $calloutSeverity issue(s) this sweep:**")
foreach ($g in $topGroups) {
$f = $g.Group[0]
$srvCount = @($g.Group | ForEach-Object { $_.Server } | Sort-Object -Unique).Count
$findingLine = ($f.Finding -replace "`r?`n", " ")
[void]$report.AppendLine("> - $(Get-SeverityEmoji $calloutSeverity) **[$($f.Category)]** $findingLine *($srvCount server(s))*")
}
[void]$report.AppendLine("")
}
# Fleet scoreboard.
# Per-server detail sections are unreadable past a handful of instances --
# this is the "which boxes do I look at first" table, worst grade first.
$scoreboard = [System.Collections.Generic.List[PSObject]]::new()
foreach ($server in $AllResults.Keys) {
$data = $AllResults[$server]
$display = Get-DisplayName $server
$overall = $null
if ($data.Dashboard -and $data.Dashboard.Rows.Count -gt 0) {
$overall = @($data.Dashboard.Rows | Where-Object {
(Get-CellValue -Row $_ -Column "Category") -eq "OVERALL"
})[0]
# Older Diag builds may not tag an OVERALL row; fall back to the first.
if (-not $overall) { $overall = $data.Dashboard.Rows[0] }
}
$serverRecs = @($AllRecommendations | Where-Object { $_.Server -eq $display })
$score = Get-CellValue -Row $overall -Column "Score"
$scoreboard.Add([PSCustomObject]@{
Server = $display
Grade = [string](Get-CellValue -Row $overall -Column "Grade")
Score = $score
SortKey = if ($null -ne $score) { [int]$score } else { 999 }
Critical = @($serverRecs | Where-Object { $_.Severity -eq "CRITICAL" }).Count
Warning = @($serverRecs | Where-Object { $_.Severity -eq "WARNING" }).Count
Headline = [string](Get-CellValue -Row $overall -Column "Headline")
})
}
if ($scoreboard.Count -gt 0) {
[void]$report.AppendLine("## Fleet Scoreboard")
[void]$report.AppendLine("")
[void]$report.AppendLine("| Server | Grade | Score | CRITICAL | WARNING | Headline |")
[void]$report.AppendLine("| --- | --- | --- | --- | --- | --- |")
$ranked = $scoreboard | Sort-Object -Property @{ Expression = "SortKey" },
@{ Expression = "Critical"; Descending = $true },
@{ Expression = "Server" }
foreach ($row in $ranked) {
$headline = $row.Headline -replace '\|', '\|' -replace "`n", " "
$scoreText = if ($null -ne $row.Score) { $row.Score } else { "N/A" }
$gradeText = Get-GradeBadge $row.Grade
[void]$report.AppendLine("| $($row.Server) | $gradeText | $scoreText | $($row.Critical) | $($row.Warning) | $headline |")
}
[void]$report.AppendLine("")
}