-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGet-ComputerHealth.ps1
More file actions
1867 lines (1578 loc) · 65.5 KB
/
Copy pathGet-ComputerHealth.ps1
File metadata and controls
1867 lines (1578 loc) · 65.5 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
Runs a suite of built-in and optional custom "HealthTest-*" checks and reports their findings; can also whitelist/suppress expected messages by signature.
.DESCRIPTION
Executes many health-test functions (named `HealthTest-*`) and emits their results either as structured objects (`-OutputObjects`) and/or as colorized console messages (`-OutputConsoleMessages`), with optional filtering via `-Hide`.
Supports:
- Listing available built-in tests (`-ListAllBuiltInTests`).
- Running only selected tests (`-OnlyTheseTests`) and/or skipping specific tests (`-ExcludeTests`).
- Running custom tests by executing `.ps1` files directly. `-IncludeTestsFromFolder` remains as a deprecated compatibility parameter that selects which custom scripts to run.
- Suppressing expected notices/warnings/failures by 8-hex "signature" hashes, either temporarily for the current run (`-WhitelistSigs`) or by appending a permanent suppression entry (`-AddWhitelisting`) to a suppression file.
- Requiring specific findings from selected tests. If a required signature is not emitted when that test runs, a failure is emitted. Required findings are stored in `.\config\required_findings.psd1` and can be updated with `-SetAsRequired`.
When `-OutputObjects` is used, each emitted log object includes these fields:
- `TimeUtc` (UTC timestamp for the message; intended for cross-machine sorting/aggregation and report export as UTC)
- `Computer`, `Level`, `Message`, `Hash`, `Suppressed`, `Comment`, `Emitter`
Notable side effects:
- When custom tests are selected, the `.ps1` files are executed directly.
- The health tests themselves may perform read/write operations depending on their implementation (this script invokes them; it does not enforce read-only behavior).
Idempotency:
- `-AddWhitelisting` is append-only (not strictly idempotent): repeated runs add additional lines; last matching line "wins" when loading suppressions.
- `-SetAsRequired` updates or creates a single required-finding entry for the specified test/signature pair.
Dependencies & execution context:
- Requires elevation.
- Relies on companion scripts: `lib-write-log-objects.ps1` and the modules/helpers under `health-tests\*.ps1` dot-sourced below.
- Uses a suppression config file at `.\config\Get-ComputerHealth.sigs-to-suppress.txt`.
- Uses a required-findings config file at `.\config\required_findings.psd1`.
.PARAMETER RunWithoutElevation
(Parameter sets: Run, AddWhitelist, SetRequired, List) Bypasses the normal elevation requirement. Default behavior still requires running as Administrator.
.PARAMETER OutputConsoleMessages
(Parameter set: Run) If set, writes colorized log/messages to the console while executing tests.
.PARAMETER OutputObjects
(Parameter set: Run) If set, outputs structured objects produced by the health tests to the pipeline.
.PARAMETER Hide
(Parameter set: Run) Message visibility filter. String containing only letters from `DIPNWFSC`.
Default: empty (show all). Typical value: `DIP`
D = hide Debug messages
I = hide Info messages
P = hide Pass messages
N = hide Notice messages
W = hide Warning messages
F = hide Failure messages
C = hide Comments (messages still print, but without their Comment lines)
.PARAMETER WhitelistSigs
(Parameter set: Run) One or more 8-hex signatures to suppress for this run only (merged into the loaded suppression set).
.PARAMETER OnlyTheseTests
(Parameter set: Run) One or more built-in function names and/or custom `.ps1` script names/paths to execute (treated as a list; values may be space/comma separated). When provided, only these tests are invoked.
.PARAMETER ExcludeTests
(Parameter set: Run) One or more function names to skip (treated as a list; values may be space/comma separated).
.PARAMETER IncludeTestsFromFolder
(Parameter set: Run) Deprecated compatibility parameter. Path to a folder containing custom `.ps1` scripts (or a single `.ps1` path). Matching files are executed directly.
.PARAMETER SkipSlowTests
(Parameter set: Run) Skips health tests that have high time impact (`Impact: ... High(Time)` in their help block).
.PARAMETER DebugSkipSlowTests
(Parameter set: Run) Alias for `-SkipSlowTests` (kept for backward compatibility).
.PARAMETER SkipPolicyTests
(Parameter set: Run) Skips health tests tagged as policy inventory tests (`Tags: Policy` in their help block), such as `HealthTest-ListInstalledPrograms`.
.PARAMETER DontAutosetPolicy
(Parameter set: Run) Disables first-run auto-baselining for policy tests (`Tags: Policy`, e.g. `HealthTest-ListInstalledPrograms`). By default, first run auto-suppresses emitted `[NOTICE]`/`[WARNING]` findings for each policy test and records a marker in the suppression file. The marker includes the policy baseline version from the test help block (`Policy baseline version: N`, default 0) so a rewritten list test can establish a fresh baseline when the version is intentionally increased. Legacy markers without a baseline value are treated as baseline version 1.
.PARAMETER IpsOfAllDcs
(Parameter set: Run) Optional list of Domain Controller IP addresses passed in by the orchestrator. Stored in `$Global:GchData.IpsOfAllDcs` for health tests that need it.
.PARAMETER DoNothing
(Parameter set: Run) Immediate no-op return (useful for smoke-testing invocation/parameter binding).
.PARAMETER AddWhitelisting
(Parameter set: AddWhitelist) Appends a suppression entry for a specific signature to the suppression file and exits (does not run health tests).
.PARAMETER SetAsRequired
(Parameter set: SetRequired) Adds or updates a required-finding entry in `.\config\required_findings.psd1` and exits (does not run health tests).
.PARAMETER ComputerName
(Parameter sets: AddWhitelist, SetRequired; Mandatory) Target computer name for the change. Must match the current computer `$env:COMPUTERNAME`.
.PARAMETER Signature
(Parameter sets: AddWhitelist, SetRequired; Mandatory) 8-hex signature to suppress or require (case-insensitive). Alias: `-Sig`.
.PARAMETER Test
(Parameter set: SetRequired; Mandatory) Health test name that must emit the required signature. You can use the short test name (for example `ListListeningPorts`) or the full function name (`HealthTest-ListListeningPorts`).
.PARAMETER Comment
(Parameter sets: AddWhitelist, SetRequired) Optional free text. For `-AddWhitelisting`, it is appended to the suppression line (non-ASCII characters are replaced with `?`). For `-SetAsRequired`, it becomes the stored description and the emitted failure message when the required signature is missing.
.PARAMETER Until
(Parameter set: AddWhitelist) Optional expiry date for the suppression entry in `yyyy-MM-dd` format. After this date passes, the entry is treated as expired when loading.
.PARAMETER ListAllBuiltInTests
(Parameter set: List; Mandatory) Lists all currently loaded `HealthTest-*` functions with their synopsis text and exits.
.EXAMPLE
# Run all applicable built-in tests; show console output but hide Debug/Info/Pass; also return objects:
$out = .\Get-ComputerHealth.ps1 -OutputConsoleMessages -OutputObjects -Hide DIP
$out | Out-GridView
.EXAMPLE
# List available built-in tests (name + synopsis):
.\Get-ComputerHealth.ps1 -ListAllBuiltInTests
.EXAMPLE
# Run only a small subset of tests by name:
.\Get-ComputerHealth.ps1 -OutputConsoleMessages -OnlyTheseTests HealthTest-PendingReboot,HealthTest-DisksHaveFreeSpace
.EXAMPLE
# Temporarily suppress specific signatures just for this run:
.\Get-ComputerHealth.ps1 -OutputConsoleMessages -WhitelistSigs 1a2b3c4d,deadbeef
.EXAMPLE
# Permanently suppress a known-expected signature on this computer (optionally with expiry):
.\Get-ComputerHealth.ps1 -AddWhitelisting -ComputerName CONTOSO-SRV01 -Signature 1a2b3c4d -Comment "Known baseline deviation" -Until 2026-12-31
.EXAMPLE
# Mark a finding as required for a health test on this computer:
.\Get-ComputerHealth.ps1 -SetAsRequired -ComputerName CONTOSO-SRV01 -Test ListListeningPorts -Signature bfc162fa -Comment "Port 443(IIS) should be listening but is not"
.NOTES
- Elevation is enforced for normal runs, whitelisting operations, and required-finding updates.
- `-RunWithoutElevation` bypasses the elevation guard; some health tests may still fail or produce incomplete results when run non-elevated.
- Permanent suppression file: `.\config\Get-ComputerHealth.sigs-to-suppress.txt`.
- Required findings file: `.\config\required_findings.psd1`.
- Custom tests: scripts may execute arbitrary code when run.
#>
[CmdletBinding(DefaultParameterSetName = 'Run')]
param(
[Parameter(ParameterSetName = 'PrettifyWarning')]
[Alias('Prettify')]
[switch]$PrettifyWriteWarning,
[Parameter(ParameterSetName = 'PrettifyWarning', ValueFromPipeline = $true)]
[AllowNull()]
[object]$InputObject,
# ----------------------------
# Normal run (execute tests)
# ----------------------------
[Parameter(ParameterSetName = 'Run')]
[switch]$OutputConsoleMessages,
[Parameter(ParameterSetName = 'Run')]
[switch]$OutputObjects,
[Parameter(ParameterSetName = 'Run')]
[ValidatePattern('(?i)^[DIPNWFSC]*$')]
[string]$Hide = '',
[Parameter(ParameterSetName = 'Run')]
[Alias('SuppressSigs')]
[string[]]$WhitelistSigs = @(),
[Parameter(ParameterSetName = 'Run')]
[string[]]$OnlyTheseTests = @(),
[Parameter(ParameterSetName = 'Run')]
[string[]]$ExcludeTests = @(),
[Parameter(ParameterSetName = 'Run')]
[string]$IncludeTestsFromFolder,
[Parameter(ParameterSetName = 'Run')]
[Alias('DebugSkipSlowTests')]
[switch]$SkipSlowTests,
[Parameter(ParameterSetName = 'Run')]
[switch]$SkipPolicyTests,
[Parameter(ParameterSetName = 'Run')]
[Alias('Quick')]
[switch]$SkipNonEssentialTests,
[Parameter(ParameterSetName = 'Run')]
[switch]$DontAutosetPolicy,
[Parameter(ParameterSetName = 'Run')]
[string[]]$IpsOfAllDcs = @(),
[Parameter(ParameterSetName = 'Run')]
[switch]$DoNothing,
[Parameter(ParameterSetName = 'Run')]
[Parameter(ParameterSetName = 'AddWhitelist')]
[Parameter(ParameterSetName = 'SetRequired')]
[Parameter(ParameterSetName = 'List')]
[switch]$RunWithoutElevation,
# ----------------------------
# Add whitelisting entry
# ----------------------------
[Parameter(ParameterSetName = 'AddWhitelist', Mandatory)]
[switch]$AddWhitelisting,
[Parameter(ParameterSetName = 'SetRequired', Mandatory)]
[switch]$SetAsRequired,
[Parameter(ParameterSetName = 'AddWhitelist', Mandatory)]
[Parameter(ParameterSetName = 'SetRequired', Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[Parameter(ParameterSetName = 'AddWhitelist', Mandatory)]
[Parameter(ParameterSetName = 'SetRequired', Mandatory)]
[Alias('Sig')]
[ValidatePattern('^[0-9A-Fa-f]{8}$')]
[string]$Signature,
[Parameter(ParameterSetName = 'AddWhitelist')]
[Parameter(ParameterSetName = 'SetRequired')]
[string]$Comment,
[Parameter(ParameterSetName = 'AddWhitelist')]
[ValidatePattern('^\d{4}-\d{2}-\d{2}$')]
[string]$Until,
[Parameter(ParameterSetName = 'SetRequired', Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Test,
# ----------------------------
# List tests
# ----------------------------
[Parameter(ParameterSetName = 'List', Mandatory)]
[switch]$ListAllBuiltInTests
)
$VERSION="8.11.2"
if ($null -ne $Hide) {
$Hide = ([string]$Hide).ToUpperInvariant()
}
$SCRIPT_BIN_DIR = (Resolve-Path -LiteralPath $PSScriptRoot).Path
$ROOT_DIR = Split-Path -Parent $SCRIPT_BIN_DIR
$CONFIG_DIR = Join-Path $ROOT_DIR 'config'
#------------------------------------------
# Configuration
#
$script:Config = [pscustomobject]@{
SuppressSignaturesPath = Join-Path $CONFIG_DIR 'Get-ComputerHealth.sigs-to-suppress.txt'
RequiredFindingsPath = Join-Path $CONFIG_DIR 'required_findings.psd1'
DefaultCustomTestsPath = Join-Path $CONFIG_DIR 'Custom-HealthTests'
}
#------------------------------------------
# Dot source libraries of functions
#
. (Join-Path -Path $PSScriptRoot -ChildPath "lib-write-log-objects.ps1")
. (Join-Path -Path $PSScriptRoot -ChildPath "health-tests\helpers-for-healthtests.ps1")
#------------------------------------------
# Helper functions specific to this script except tests
#
function Add-AsciiLine {
# Append a line to an ASCII file (replaces non ASCII chars with ?)
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$Line
)
# Replace non-ASCII chars (anything > 0x7F) with '?'
$safeLine = ($Line -replace '[^\u0000-\u007F]', '?')
# Append using ASCII encoding
Add-Content -LiteralPath $Path -Value $safeLine -Encoding ASCII
}
function Get-RequiredFindingConfigKeys {
[CmdletBinding()]
param($Config)
if ($null -eq $Config) {
return @()
}
if ($Config -is [System.Collections.IDictionary]) {
return @($Config.Keys)
}
return @($Config.PSObject.Properties.Name)
}
function Test-RequiredFindingConfigKey {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Config,
[Parameter(Mandatory)][string]$Key
)
if ($Config -is [System.Collections.IDictionary]) {
return $Config.Contains($Key)
}
return ($Config.PSObject.Properties[$Key] -ne $null)
}
function Get-RequiredFindingConfigValue {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Config,
[Parameter(Mandatory)][string]$Key
)
if ($Config -is [System.Collections.IDictionary]) {
return $Config[$Key]
}
return $Config.$Key
}
function Normalize-RequiredFindingTestName {
[CmdletBinding()]
param(
[AllowEmptyString()][string]$TestName
)
$normalized = [string]$TestName
if ([string]::IsNullOrWhiteSpace($normalized)) {
return ''
}
$normalized = $normalized.Trim()
if ($normalized -match '^(?i)HealthTest-(.+)$') {
$normalized = $Matches[1]
}
return $normalized.Trim()
}
function Convert-RequiredFindingEntryToHashtable {
[CmdletBinding()]
param(
$Entry
)
$description = ''
if (($null -ne $Entry) -and (Test-RequiredFindingConfigKey -Config $Entry -Key 'Description')) {
$description = [string](Get-RequiredFindingConfigValue -Config $Entry -Key 'Description')
}
$timestamp = $null
if (($null -ne $Entry) -and (Test-RequiredFindingConfigKey -Config $Entry -Key 'Ts')) {
$timestampValue = Get-RequiredFindingConfigValue -Config $Entry -Key 'Ts'
if ($timestampValue -is [datetime]) {
$timestamp = [datetime]$timestampValue
}
elseif ($null -ne $timestampValue) {
$parsedTimestamp = [datetime]::MinValue
if ([datetime]::TryParse([string]$timestampValue, [ref]$parsedTimestamp)) {
$timestamp = $parsedTimestamp
}
}
}
$user = ''
if (($null -ne $Entry) -and (Test-RequiredFindingConfigKey -Config $Entry -Key 'User')) {
$user = [string](Get-RequiredFindingConfigValue -Config $Entry -Key 'User')
}
return [ordered]@{
Description = $description
Ts = $timestamp
User = $user
}
}
function Read-RequiredFindingsConfig {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path
)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return [ordered]@{}
}
try {
$rawText = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop
$scriptBlock = [scriptblock]::Create($rawText)
$rawConfig = & $scriptBlock
}
catch {
throw "Failed reading required findings configuration file '$Path': $($_.Exception.Message)"
}
$config = [ordered]@{}
foreach ($testKey in @(Get-RequiredFindingConfigKeys -Config $rawConfig | Sort-Object)) {
$normalizedTestName = Normalize-RequiredFindingTestName -TestName ([string]$testKey)
if ([string]::IsNullOrWhiteSpace($normalizedTestName)) {
continue
}
$rawTestFindings = Get-RequiredFindingConfigValue -Config $rawConfig -Key $testKey
$testFindings = [ordered]@{}
foreach ($signatureKey in @(Get-RequiredFindingConfigKeys -Config $rawTestFindings | Sort-Object)) {
$signatureText = ([string]$signatureKey).Trim().ToLowerInvariant()
if ($signatureText -notmatch '^[0-9a-f]{8}$') {
throw "Invalid required finding signature '$signatureKey' in '$Path' for test '$normalizedTestName'."
}
$rawEntry = Get-RequiredFindingConfigValue -Config $rawTestFindings -Key $signatureKey
$testFindings[$signatureText] = Convert-RequiredFindingEntryToHashtable -Entry $rawEntry
}
if ($testFindings.Count -gt 0) {
$config[$normalizedTestName] = $testFindings
}
}
return $config
}
function ConvertTo-RequiredFindingsPowerShellString {
[CmdletBinding()]
param(
[AllowNull()][string]$Text
)
$value = [string]$Text
return ("'" + ($value -replace "'", "''") + "'")
}
function Save-RequiredFindingsConfig {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)]$RequiredFindings
)
$lines = New-Object System.Collections.Generic.List[string]
$lines.Add('@{') | Out-Null
foreach ($testName in @(Get-RequiredFindingConfigKeys -Config $RequiredFindings | Sort-Object)) {
$testFindings = Get-RequiredFindingConfigValue -Config $RequiredFindings -Key $testName
$lines.Add((" {0} = @{{" -f (ConvertTo-RequiredFindingsPowerShellString -Text ([string]$testName)))) | Out-Null
foreach ($signature in @(Get-RequiredFindingConfigKeys -Config $testFindings | Sort-Object)) {
$entry = Convert-RequiredFindingEntryToHashtable -Entry (Get-RequiredFindingConfigValue -Config $testFindings -Key $signature)
$timestamp = $entry.Ts
if ($null -eq $timestamp) {
$timestamp = Get-Date
}
$lines.Add((
" {0} = @{{Description = {1}; Ts = [datetime]{2}; User = {3}}};" -f
(ConvertTo-RequiredFindingsPowerShellString -Text ([string]$signature).ToLowerInvariant()),
(ConvertTo-RequiredFindingsPowerShellString -Text $entry.Description),
(ConvertTo-RequiredFindingsPowerShellString -Text ($timestamp.ToString('yyyy-MM-dd HH:mm'))),
(ConvertTo-RequiredFindingsPowerShellString -Text $entry.User)
)) | Out-Null
}
$lines.Add(' };') | Out-Null
}
$lines.Add('}') | Out-Null
$parentDir = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parentDir) -and (-not (Test-Path -LiteralPath $parentDir -PathType Container))) {
New-Item -ItemType Directory -Path $parentDir -Force | Out-Null
}
Set-Content -LiteralPath $Path -Value $lines -Encoding UTF8
}
function Set-RequiredFindingEntry {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$TestName,
[Parameter(Mandatory)][string]$Signature,
[string]$Description,
[datetime]$Timestamp = (Get-Date),
[string]$User = $(
try {
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
}
catch {
[string]$env:USERNAME
}
)
)
$normalizedTestName = Normalize-RequiredFindingTestName -TestName $TestName
if ([string]::IsNullOrWhiteSpace($normalizedTestName)) {
throw "You must supply a -Test"
}
$normalizedSignature = ([string]$Signature).Trim().ToLowerInvariant()
if ($normalizedSignature -notmatch '^[0-9a-f]{8}$') {
throw "Invalid -Signature: $Signature"
}
$config = Read-RequiredFindingsConfig -Path $Path
if (-not (Test-RequiredFindingConfigKey -Config $config -Key $normalizedTestName)) {
$config[$normalizedTestName] = [ordered]@{}
}
if (Test-RequiredFindingConfigKey -Config $config[$normalizedTestName] -Key $normalizedSignature) {
$existingEntry = Convert-RequiredFindingEntryToHashtable -Entry $config[$normalizedTestName][$normalizedSignature]
if ([string]$existingEntry.Description -ceq [string]$Description) {
return
}
}
$config[$normalizedTestName][$normalizedSignature] = [ordered]@{
Description = [string]$Description
Ts = $Timestamp
User = [string]$User
}
Save-RequiredFindingsConfig -Path $Path -RequiredFindings $config
}
function Get-RequiredFindingsForTest {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$RequiredFindings,
[Parameter(Mandatory)][string]$FunctionName
)
$shortName = Normalize-RequiredFindingTestName -TestName $FunctionName
$keysToTry = @($FunctionName, "HealthTest-$shortName", $shortName)
foreach ($key in $keysToTry) {
if ([string]::IsNullOrWhiteSpace($key)) {
continue
}
if (Test-RequiredFindingConfigKey -Config $RequiredFindings -Key $key) {
return (Get-RequiredFindingConfigValue -Config $RequiredFindings -Key $key)
}
}
return $null
}
function Get-MissingRequiredFindings {
[CmdletBinding()]
param(
[Parameter(Mandatory)][object[]]$Records,
[Parameter(Mandatory)]$RequiredFindingsForTest
)
$emittedSignatures = @(
$Records |
Where-Object { $_ -and $_.PSObject.Properties['Hash'] } |
ForEach-Object { ([string]$_.Hash).Trim().ToLowerInvariant() } |
Where-Object { $_ -match '^[0-9a-f]{8}$' } |
Sort-Object -Unique
)
$missing = New-Object System.Collections.Generic.List[object]
foreach ($signature in @(Get-RequiredFindingConfigKeys -Config $RequiredFindingsForTest | Sort-Object)) {
$normalizedSignature = ([string]$signature).Trim().ToLowerInvariant()
if ($normalizedSignature -notin $emittedSignatures) {
$entry = Convert-RequiredFindingEntryToHashtable -Entry (Get-RequiredFindingConfigValue -Config $RequiredFindingsForTest -Key $signature)
$missing.Add([pscustomobject]@{
Signature = $normalizedSignature
Description = [string]$entry.Description
Ts = $entry.Ts
User = [string]$entry.User
}) | Out-Null
}
}
return $missing.ToArray()
}
function Invoke-RequiredFindingsValidation {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$FunctionName,
[Parameter(Mandatory)][object[]]$Records,
[Parameter(Mandatory)]$RequiredFindings
)
$requiredFindingsForTest = Get-RequiredFindingsForTest -RequiredFindings $RequiredFindings -FunctionName $FunctionName
if ($null -eq $requiredFindingsForTest) {
return @($Records)
}
$shortName = Normalize-RequiredFindingTestName -TestName $FunctionName
$missingFindings = @(Get-MissingRequiredFindings -Records $Records -RequiredFindingsForTest $requiredFindingsForTest)
if ($missingFindings.Count -eq 0) {
return @($Records)
}
$validationFailures = @()
foreach ($missingFinding in $missingFindings) {
$failureMessage = [string]$missingFinding.Description
if ([string]::IsNullOrWhiteSpace($failureMessage)) {
$failureMessage = "Required finding with signature $($missingFinding.Signature) was not emitted."
}
$validationFailures += Log-Failure $failureMessage -Comment "Required finding with signature $($missingFinding.Signature) was not emitted by $shortName" -Emitter $FunctionName
}
return @($Records) + @($validationFailures)
}
function Invoke-HealthTest {
<#
.SYNOPSIS
Invoke a named health-test function and return a structured result object.
.OUTPUTS
[pscustomobject] with properties:
FunctionName, Time, ElapsedMilliseconds, Output, Success, Error, Category, Reason, FullyQualifiedErrorId, ScriptStackTrace
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$FunctionName
)
$metaForExclude = Get-HealthTestTagsMetadata -FunctionName $FunctionName
$markTestMessagesSuppressed = 'Suppressed' -in $metaForExclude.Tags
$baseFunctionName = "HealthTest-$($metaForExclude.TestName)"
if (($ExcludeTests -contains $FunctionName) -or ($ExcludeTests -contains $baseFunctionName) -or ($ExcludeTests -contains $metaForExclude.TestName)) {
Log-Debug "Skipping test $FunctionName"
return
}
Write-Progress -Activity "Starting test $FunctionName"
Log-debug "Starting test $FunctionName"
$cmd = Get-Command -Name $FunctionName -CommandType Function -ErrorAction SilentlyContinue
if (-not $cmd) {
Log-failure "(Program Error) Health test function '$FunctionName' not found"
return
}
$target = (Get-Item ("Function:\{0}" -f $cmd.Name)).ScriptBlock
$oldEap = $ErrorActionPreference
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
$cntProperRecord = 0
$cntImproperRecord = 0
$legacyLogDetected = $false
$supplementalOutputLines = New-Object 'System.Collections.Generic.List[string]'
$pendingOutputRecords = New-Object 'System.Collections.Generic.List[object]'
$ErrorActionPreference = 'Stop'
$result = & {
$WarningPreference = 'Continue'
& $target 3>&1
}
foreach ($item in $result) {
if ($item -is [System.Management.Automation.WarningRecord]) {
$record = Convert-WarningLikeObjectToLogRecord -Value $item
[void]$pendingOutputRecords.Add([pscustomobject]@{
Type = 'warning'
Value = $record
})
$cntProperRecord += 1
}
elseif ($item -and $item.PSObject.Properties['Hash'] -and $null -ne $item.PSObject.Properties['Message'] -and $item.PSObject.Properties['level']) {
$legacyLogDetected = $true
$cntProperRecord += 1
if ($markTestMessagesSuppressed -and ([string]$item.level).ToLowerInvariant() -ne 'debug') {
$item | Add-Member -NotePropertyName Suppressed -NotePropertyValue $true -Force
}
[void]$pendingOutputRecords.Add([pscustomobject]@{
Type = 'legacy'
Value = $item
})
}
elseif ($item -is [string]) {
$text = [string]$item
if (-not [string]::IsNullOrWhiteSpace($text)) {
[void]$supplementalOutputLines.Add($text.Trim())
}
}
else {
$objType = $item.GetType().FullName
$objText = ($item | Out-String).Trim()
if ([string]::IsNullOrWhiteSpace($objText)) { $objText = '<empty object serialization>' }
[void]$supplementalOutputLines.Add("Converted output object of type $objType")
[void]$supplementalOutputLines.Add($objText)
}
}
$lastWarningEntry = $null
for ($i = $pendingOutputRecords.Count - 1; $i -ge 0; $i--) {
if ($pendingOutputRecords[$i].Type -eq 'warning') {
$lastWarningEntry = $pendingOutputRecords[$i]
break
}
}
if ($supplementalOutputLines.Count -gt 0) {
if ($null -ne $lastWarningEntry) {
$existingComment = [string]$lastWarningEntry.Value.Comment
$supplementalComment = (Compress-HealthDiagnosticOutputLines -Lines @($supplementalOutputLines)) -join "`n"
if (-not [string]::IsNullOrWhiteSpace($supplementalComment)) {
if ([string]::IsNullOrWhiteSpace($existingComment)) {
$lastWarningEntry.Value.Comment = $supplementalComment
}
else {
$lastWarningEntry.Value.Comment = $existingComment.TrimEnd() + "`n" + $supplementalComment
}
}
}
else {
foreach ($supplementalLine in $supplementalOutputLines) {
if ([string]::IsNullOrWhiteSpace($supplementalLine)) { continue }
$parts = Convert-TextToLogRecord $supplementalLine
$cntImproperRecord += 1
Log-Debug $parts.Message -Comment $parts.Comment
}
}
}
foreach ($pendingRecord in $pendingOutputRecords) {
if ($pendingRecord.Type -eq 'warning') {
$record = $pendingRecord.Value
Log-Msg -Level $record.Level -Msg $record.Msg -Comment $record.Comment -Emitter $FunctionName -Suppressed:$markTestMessagesSuppressed
}
else {
Write-Output $pendingRecord.Value
}
}
if ($legacyLogDetected) {
$sourceScript = $cmd.ScriptBlock.File
$sourceLabel = if ([string]::IsNullOrWhiteSpace($sourceScript)) { "function '$FunctionName'" } else { "script '$sourceScript'" }
Log-Notice "Consider modernizing the code in $sourceLabel to use Write-Warning instead of Log-Pass/Log-Failure/..."
}
if ($cntProperRecord -eq 0 -and $cntImproperRecord -eq 0) {
Log-notice "$FunctionName returned no output (this is due to a programmer's mistake; the test may or may not have passed)"
}
}
catch {
$err = $_
$inv = $err.InvocationInfo
# Try to locate the inner (real) throw site from the script stack trace
$innerFunc = $null; $innerFile = $null; $innerLine = $null; $innerCode = $null
# The ScriptStackTrace has lines like:
# "at HealthTest-Whatever, C:\path\Module.psm1: line 123"
$frames = ($err.ScriptStackTrace -split "`r?`n") |
Where-Object { $_ -match ':\s*line\s+\d+' }
# Prefer the first frame that is NOT this wrapper function
$frame = $frames | Where-Object { $_ -notmatch '\bInvoke-HealthTest\b' } | Select-Object -First 1
if (-not $frame) { $frame = $frames | Select-Object -First 1 } # fallback
if ($frame -and $frame -match '^(?:at\s+)?([^,]+),\s*(.+?):\s*line\s+(\d+)\s*$') {
$innerFunc = $matches[1].Trim()
$innerFile = $matches[2].Trim()
$innerLine = [int]$matches[3]
# Try to fetch the actual source line (best-effort)
try {
if ($innerFile -and (Test-Path -LiteralPath $innerFile)) {
$innerCode = (Get-Content -LiteralPath $innerFile -TotalCount $innerLine)[-1]
}
}
catch { Log-Debug "Program Error: Failed to fetch the actual source line" }
}
# Build a helpful message with graceful fallbacks
$baseMsg = Get-LeftString $err.Exception.GetBaseException().Message 500
$outerLine = $inv.ScriptLineNumber
$outerCode = $inv.Line
$details =
if ($innerLine -and $innerFunc) {
"Throw site: $innerFunc" +
($(if ($innerFile) { "`nFile: $innerFile" } else { "" })) +
"`nLine: $innerLine" +
($(if ($innerCode) { "`n # Code: $innerCode" } else { "" }))
}
else {
# Fallback to the catcher's position info
"Throw site unknown from stack; fallback to caller:`n # Line #$($outerLine): $outerCode"
}
Log-Failure "(Program Error) Exception while running '$FunctionName'" `
-Comment "details: $baseMsg`n$details`nA Program Error during a test means either that the test failed or that its code has a bug." `
-Emitter $(if ($innerFunc) { $innerFunc } else { $FunctionName })
}
finally {
$sw.Stop()
$ErrorActionPreference = $oldEap
Write-Progress -Activity "Starting test $FunctionName" -Completed
}
Log-debug "Done with test $FunctionName in $([int]$sw.ElapsedMilliseconds) ms"
}
function Get-CustomTestScriptReferenceComment {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$ScriptPath
)
"(see custom test '$ScriptPath')"
}
function Add-CustomTestScriptReferenceComment {
[CmdletBinding()]
param(
[AllowEmptyString()][string]$Comment = '',
[Parameter(Mandatory)][string]$ScriptPath
)
$reference = Get-CustomTestScriptReferenceComment -ScriptPath $ScriptPath
$trimmedComment = [string]$Comment
if ([string]::IsNullOrWhiteSpace($trimmedComment)) {
return $reference
}
$trimmedComment = $trimmedComment.Trim()
if ($trimmedComment -match [regex]::Escape($reference)) {
return $trimmedComment
}
return ($trimmedComment + "`n" + $reference)
}
function Get-CustomHealthTestFilesFromPath {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path
)
$resolved = $null
try {
$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
}
catch {
Log-Debug "Path '$Path' was not found while resolving custom health tests."
return @()
}
if (Test-Path -LiteralPath $resolved -PathType Container) {
return @(Get-ChildItem -LiteralPath $resolved -Filter *.ps1 -File -ErrorAction SilentlyContinue | Sort-Object FullName)
}
if ((Test-Path -LiteralPath $resolved -PathType Leaf) -and ($resolved -like '*.ps1')) {
return @((Get-Item -LiteralPath $resolved -ErrorAction SilentlyContinue))
}
Log-Debug "Path '$Path' was ignored because it is neither a folder nor a .ps1 script."
return @()
}
function Resolve-CustomHealthTestScriptSelection {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Selection,
[string]$CustomTestsPath
)
if ([string]::IsNullOrWhiteSpace($Selection)) {
return $null
}
$trimmedSelection = $Selection.Trim()
if ($trimmedSelection -notlike '*.ps1') {
return $null
}
if (($trimmedSelection -match '^[.][\\/]') -or
($trimmedSelection -match '^[.][.][\\/]') -or
($trimmedSelection -match '[\\/]') -or
[System.IO.Path]::IsPathRooted($trimmedSelection)) {
$resolvedBySelection = Resolve-Path -LiteralPath $trimmedSelection -ErrorAction SilentlyContinue
if ($resolvedBySelection -and (Test-Path -LiteralPath $resolvedBySelection.Path -PathType Leaf)) {
return (Get-Item -LiteralPath $resolvedBySelection.Path -ErrorAction SilentlyContinue)
}
return $null
}
$candidateRoots = @()
if (-not [string]::IsNullOrWhiteSpace($CustomTestsPath)) {
$candidateRoots += $CustomTestsPath
}
if ($script:Config.DefaultCustomTestsPath -and ($script:Config.DefaultCustomTestsPath -notin $candidateRoots)) {
$candidateRoots += $script:Config.DefaultCustomTestsPath
}
foreach ($candidateRoot in $candidateRoots) {
$files = @(Get-CustomHealthTestFilesFromPath -Path $candidateRoot)
$match = $files | Where-Object { $_.Name -ieq $trimmedSelection } | Select-Object -First 1
if ($match) {
return $match
}
}
return $null
}
function Invoke-CustomHealthTestScript {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$ScriptPath
)
if (($ExcludeTests -contains $ScriptPath) -or
($ExcludeTests -contains (Split-Path -Leaf $ScriptPath))) {
Log-Debug "Skipping custom test $ScriptPath"
return
}
Write-Progress -Activity "Starting custom test $ScriptPath"
Log-Debug "Starting custom test $ScriptPath"
$oldEap = $ErrorActionPreference
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
$cntProperRecord = 0
$cntImproperRecord = 0
$legacyLogDetected = $false
$ErrorActionPreference = 'Stop'
$result = & {
$WarningPreference = 'Continue'
& $ScriptPath 3>&1
}
foreach ($item in $result) {
if ($item -is [System.Management.Automation.WarningRecord]) {
$record = Convert-WarningLikeObjectToLogRecord -Value $item
$comment = Add-CustomTestScriptReferenceComment -Comment $record.Comment -ScriptPath $ScriptPath
Log-Msg -Level $record.Level -Msg $record.Msg -Comment $comment -Emitter $ScriptPath
$cntProperRecord += 1
}
elseif ($item -and $item.PSObject.Properties['Hash'] -and $null -ne $item.PSObject.Properties['Message'] -and $item.PSObject.Properties['level']) {
$legacyLogDetected = $true
$cntProperRecord += 1
$existingComment = ''
if ($item.PSObject.Properties['Comment']) {
$existingComment = [string]$item.Comment
}
$item | Add-Member -NotePropertyName Comment -NotePropertyValue (Add-CustomTestScriptReferenceComment -Comment $existingComment -ScriptPath $ScriptPath) -Force
$item | Add-Member -NotePropertyName Emitter -NotePropertyValue $ScriptPath -Force
Write-Output $item
}
elseif ($item -is [string]) {
$parts = Convert-TextToLogRecord $item
$cntImproperRecord += 1
Log-Debug $parts.Message -Comment $parts.Comment -Emitter $ScriptPath
}
else {
$cntImproperRecord += 1
$objType = $item.GetType().FullName
$objText = ($item | Out-String).Trim()
if ([string]::IsNullOrWhiteSpace($objText)) { $objText = '<empty object serialization>' }
Log-Debug "Converted output object of type $objType" -Comment $objText -Emitter $ScriptPath
}
}
if ($legacyLogDetected) {
$legacyComment = Add-CustomTestScriptReferenceComment -ScriptPath $ScriptPath
Log-Notice "Consider modernizing the code in custom test script '$ScriptPath' to use Write-Warning instead of Log-Pass/Log-Failure/..." -Comment $legacyComment -Emitter $ScriptPath
}
if ($cntProperRecord -eq 0 -and $cntImproperRecord -eq 0) {
$comment = Add-CustomTestScriptReferenceComment -ScriptPath $ScriptPath
Log-Notice "Custom test script '$ScriptPath' returned no output (this is due to a programmer's mistake; the test may or may not have passed)" -Comment $comment -Emitter $ScriptPath
}
}
catch {
$err = $_
$inv = $err.InvocationInfo
$innerFunc = $null
$innerFile = $null
$innerLine = $null
$innerCode = $null
$frames = ($err.ScriptStackTrace -split "`r?`n") |
Where-Object { $_ -match ':\s*line\s+\d+' }
$frame = $frames | Where-Object { $_ -notmatch '\bInvoke-CustomHealthTestScript\b' } | Select-Object -First 1
if (-not $frame) { $frame = $frames | Select-Object -First 1 }