-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCollect-WindowsServerConfigurationEvidence.ps1
More file actions
3744 lines (3454 loc) · 175 KB
/
Copy pathCollect-WindowsServerConfigurationEvidence.ps1
File metadata and controls
3744 lines (3454 loc) · 175 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
#Requires -Version 5.1
<#
.SYNOPSIS
Collects read-only Windows Server configuration evidence for the
driver-deployment areas operated on by the Deploy-* scripts in this
repository.
.DESCRIPTION
Collects the running OS identity and build state, pending-reboot state,
the PnP device inventory (including problem devices and the AMD / BthPan
device classes this repository targets), the driver store inventory
(pnputil /enum-drivers plus Win32_PnPSignedDriver), the project
code-signing certificate presence in the LocalMachine Root and
TrustedPublisher stores (public certificate properties only - private
keys are never read or exported), boot-security state (Secure Boot,
UEFI CA 2023 servicing registry state, test-signing / integrity-check
boot options, HVCI, WDAC SiPolicy.p7b file evidence and CiTool policy
enumeration where available), recent CodeIntegrity events, the Windows
driver setup logs (setupapi.dev.log / setupapi.setup.log), the
repository script inventory (versions and SHA-256 of the four Deploy-*
scripts and this collector) and a workspace inventory (the four
WorkRoot trees and run-artifact archives, inventoried by name only -
bulk payload is never copied).
The collector is standalone and read-only: it does not install anything
and does not change system state. Evidence is written to a timestamped
directory, summarized in summary.json (schema-versioned), summary.txt
and assessment-report.txt, then zipped. At completion a color-coded
assessment report with PASS, FAIL, REVIEW and INFO items, the final
result, exit code and artifact paths is printed.
The collector can be run manually at any time, and the four Deploy-*
scripts invoke it automatically before and after their run when their
-CollectEvidence switch is set (stages 'pre' and 'post'). The stage and
the invoking script are recorded in the evidence and in the ZIP name so
pre/post pairs can be diffed.
Exit code 0 means collection completed and every assessment item is
PASS or INFO. Exit code 2 means evidence was created but at least one
item is FAIL or REVIEW. Exit code 1 means a fatal collector error.
.PARAMETER OutputRoot
Directory under which the timestamped evidence directory and ZIP are
created. The only permitted locations are the directory containing this
script and C:\Temp. When omitted, the script directory is used.
.PARAMETER Stage
Collection stage recorded in the evidence and the ZIP name:
'pre' (before a deployment run), 'post' (after a deployment run) or
'standalone' (default; manual execution).
.PARAMETER InvokedBy
Free-form identity of the invoking context (e.g.
'Deploy-AMDChipsetDriverOnWindowsServer_Install'). Recorded in the
evidence; a sanitized form is appended to the ZIP name.
.PARAMETER SkipSetupApiLog
Skips copying C:\Windows\INF\setupapi.dev.log and setupapi.setup.log
into the evidence. By default both logs are copied (size-capped at
50 MB each).
.EXAMPLE
.\Collect-WindowsServerConfigurationEvidence.ps1
.EXAMPLE
.\Collect-WindowsServerConfigurationEvidence.ps1 -Stage pre `
-InvokedBy 'Deploy-AMDGraphicsDriverOnWindowsServer_PrepareVerify'
#>
[CmdletBinding()]
param(
[Parameter()]
[AllowEmptyString()]
[string]$OutputRoot,
[Parameter()]
[ValidateSet('pre', 'post', 'standalone')]
[string]$Stage = 'standalone',
[Parameter()]
[AllowEmptyString()]
[string]$InvokedBy,
[Parameter()]
[switch]$SkipSetupApiLog
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$Script:ScriptVersion = 'collector-2026.08.09-c11'
$Script:ScriptTag = 'windows-server-configuration-evidence-collector'
$Script:ScriptHash = 'unavailable'
try {
$Script:ScriptHash = (Get-FileHash -LiteralPath $MyInvocation.MyCommand.Path -Algorithm SHA256 -ErrorAction Stop).Hash.Substring(0, 12).ToLowerInvariant()
} catch { } # psa-disable-line PSA3004 -- self-hash is identity metadata only; collection must proceed without it
$Script:ScriptShortTag = ('{0}/{1}' -f $Script:ScriptVersion, $Script:ScriptHash)
$script:SchemaVersion = 'windows-server-configuration-evidence/1.7'
# Per-stage outcome ledger (SPEC D.45). Populated by Invoke-EvidenceStage,
# written to stage-results.json, and surfaced in the assessment so a bundle
# always declares its own completeness.
$script:StageResults = New-Object 'System.Collections.Generic.List[object]'
$script:CollectorVersion = $Script:ScriptVersion
$script:MaxCopiedLogBytes = 50MB
#region Generic helpers (adapted from the iso-project post-install collector)
function Get-UtcTimestamp {
[CmdletBinding()]
[OutputType([string])]
param()
return [datetime]::UtcNow.ToString('o')
}
function Get-PropertyValue {
[CmdletBinding()]
[OutputType([object])]
param(
[Parameter()] [AllowNull()] [object]$InputObject,
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Name,
[Parameter()] [AllowNull()] [object]$DefaultValue = $null
)
if ($null -eq $InputObject) { return $DefaultValue }
$property = $InputObject.PSObject.Properties[$Name]
if ($null -eq $property) { return $DefaultValue }
return $property.Value
}
function Get-FileEvidence {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Path,
[Parameter()] [switch]$SkipHash,
[Parameter()] [switch]$SkipAuthenticode
)
$result = [pscustomobject][ordered]@{
Path = $Path
FileName = $null
Present = $false
SizeBytes = $null
CreationTimeUtc = $null
LastWriteTimeUtc = $null
FileVersion = $null
ProductVersion = $null
CompanyName = $null
Sha256 = $null
HashErrorMessage = $null
AuthenticodeStatus = $null
AuthenticodeStatusMessage = $null
SignerSubject = $null
SignerIssuer = $null
SignerThumbprint = $null
SignerNotAfter = $null
TimeStamperSubject = $null
AuthenticodeErrorMessage = $null
ReadErrorMessage = $null
}
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $result }
try {
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
$result.Path = $item.FullName
$result.FileName = [string]$item.Name
$result.Present = $true
$result.SizeBytes = [int64]$item.Length
$result.CreationTimeUtc = $item.CreationTimeUtc.ToString('o')
$result.LastWriteTimeUtc = $item.LastWriteTimeUtc.ToString('o')
try {
$versionInfo = $item.VersionInfo
if ($null -ne $versionInfo) {
$result.FileVersion = [string]$versionInfo.FileVersion
$result.ProductVersion = [string]$versionInfo.ProductVersion
$result.CompanyName = [string]$versionInfo.CompanyName
}
}
catch { } # psa-disable-line PSA3004 -- version resource is optional for data files
if (-not $SkipHash) {
try {
$result.Sha256 = (Get-FileHash -LiteralPath $item.FullName -Algorithm SHA256 -ErrorAction Stop).Hash.ToLowerInvariant()
}
catch {
$result.HashErrorMessage = $_.Exception.Message
}
}
if (-not $SkipAuthenticode) {
try {
$signature = Get-AuthenticodeSignature -LiteralPath $item.FullName -ErrorAction Stop
$result.AuthenticodeStatus = [string]$signature.Status
$result.AuthenticodeStatusMessage = [string]$signature.StatusMessage
if ($null -ne $signature.SignerCertificate) {
$result.SignerSubject = [string]$signature.SignerCertificate.Subject
$result.SignerIssuer = [string]$signature.SignerCertificate.Issuer
$result.SignerThumbprint = [string]$signature.SignerCertificate.Thumbprint
$result.SignerNotAfter = $signature.SignerCertificate.NotAfter.ToString('o')
}
$timeStamper = Get-PropertyValue -InputObject $signature -Name 'TimeStamperCertificate'
if ($null -ne $timeStamper) {
$result.TimeStamperSubject = [string]$timeStamper.Subject
}
}
catch {
$result.AuthenticodeErrorMessage = $_.Exception.Message
}
}
}
catch {
$result.ReadErrorMessage = $_.Exception.Message
}
return $result
}
function Read-CapturedText {
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Path
)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return [string]::Empty }
$content = Get-Content -LiteralPath $Path -Raw -ErrorAction SilentlyContinue
if ($null -eq $content) { return [string]::Empty }
return [string]$content
}
function Invoke-CapturedCommand {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$FilePath,
[Parameter()] [AllowNull()] [AllowEmptyCollection()] [string[]]$ArgumentList = @()
)
$arguments = @()
if ($null -ne $ArgumentList) { $arguments = @($ArgumentList) }
$stdout = [System.IO.Path]::GetTempFileName()
$stderr = [System.IO.Path]::GetTempFileName()
try {
$startParameters = @{
FilePath = $FilePath
Wait = $true
PassThru = $true
NoNewWindow = $true
RedirectStandardOutput = $stdout
RedirectStandardError = $stderr
ErrorAction = 'Stop'
}
# Windows PowerShell 5.1 rejects Start-Process -ArgumentList @().
if ($arguments.Count -gt 0) { $startParameters['ArgumentList'] = $arguments }
$process = Start-Process @startParameters
return [pscustomobject][ordered]@{
FilePath = $FilePath
Arguments = @($arguments)
Started = $true
Succeeded = ([int]$process.ExitCode -eq 0)
ExitCode = [int]$process.ExitCode
StdOut = Read-CapturedText -Path $stdout
StdErr = Read-CapturedText -Path $stderr
ErrorMessage = $null
}
}
catch {
return [pscustomobject][ordered]@{
FilePath = $FilePath
Arguments = @($arguments)
Started = $false
Succeeded = $false
ExitCode = $null
StdOut = Read-CapturedText -Path $stdout
StdErr = Read-CapturedText -Path $stderr
ErrorMessage = $_.Exception.Message
}
}
finally {
Remove-Item -LiteralPath $stdout, $stderr -Force -ErrorAction SilentlyContinue
}
}
function Get-RegistryKeySnapshot {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Path
)
$result = [pscustomobject][ordered]@{
Path = $Path
Present = $false
Available = $false
ErrorMessage = $null
Values = [pscustomobject][ordered]@{}
}
if (-not (Test-Path -LiteralPath $Path)) { return $result }
try {
$key = Get-Item -LiteralPath $Path -ErrorAction Stop
$values = [ordered]@{}
foreach ($name in @($key.GetValueNames() | Sort-Object)) {
$value = $key.GetValue($name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
$values[$name] = [pscustomobject][ordered]@{
Type = [string]$key.GetValueKind($name)
Value = $value
}
}
$result.Present = $true
$result.Available = $true
$result.Values = [pscustomobject]$values
}
catch {
$result.Present = $true
$result.ErrorMessage = $_.Exception.Message
}
return $result
}
function Get-NamedRegistryValue {
[CmdletBinding()]
[OutputType([object])]
param(
[Parameter(Mandatory = $true)] [object]$Snapshot,
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Name,
[Parameter()] [AllowNull()] [object]$DefaultValue = $null
)
if ($null -eq $Snapshot -or -not $Snapshot.Available) { return $DefaultValue }
$property = $Snapshot.Values.PSObject.Properties[$Name]
if ($null -eq $property -or $null -eq $property.Value) { return $DefaultValue }
return $property.Value.Value
}
function Write-EvidenceJson {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)] [AllowNull()] [object]$InputObject,
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$Directory,
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$FileName
)
$InputObject | ConvertTo-Json -Depth 20 |
Set-Content -LiteralPath (Join-Path $Directory $FileName) -Encoding UTF8
}
#endregion
#region Pending reboot (adapted; advisory allow-list retained from the iso collector)
function Test-PendingFileRenameAdvisoryCleanup {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string]$SourcePath
)
$normalized = $SourcePath -replace '^(?:\*1)?\\\?\?\\', ''
$patterns = @(
'(?i)^[A-Z]:\\Windows\\SystemTemp\\MicrosoftEdgeUpdate\.exe\.old\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$',
'(?i)^[A-Z]:\\Windows\\SystemTemp\\CopilotUpdate\.exe\.old\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$',
'(?i)^[A-Z]:\\Program Files \(x86\)\\Microsoft\\EdgeUpdate\\[0-9][^\\]*$'
)
foreach ($pattern in $patterns) {
if ($normalized -match $pattern) { # psa-disable-line PSA2003 -- $pattern iterates a non-null literal array defined above
return [pscustomobject][ordered]@{
IsAdvisory = $true
NormalizedSource = $normalized
Reason = 'RecognizedMicrosoftUpdaterCleanup'
}
}
}
return [pscustomobject][ordered]@{
IsAdvisory = $false
NormalizedSource = $normalized
Reason = 'UnrecognizedPendingFileOperation'
}
}
function Convert-PendingFileRenameOperationsEvidence {
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter()] [AllowNull()] [object]$Value
)
$rawValues = @()
if ($null -ne $Value) {
if ($Value -is [System.Array]) {
$rawValues = @($Value | ForEach-Object { if ($null -eq $_) { '' } else { [string]$_ } })
}
else {
$rawValues = @([string]$Value)
}
}
$records = New-Object 'System.Collections.Generic.List[object]'
$malformed = (($rawValues.Count % 2) -ne 0)
for ($index = 0; $index -lt $rawValues.Count; $index += 2) {
$source = [string]$rawValues[$index]
$hasTarget = (($index + 1) -lt $rawValues.Count)
$target = if ($hasTarget) { [string]$rawValues[$index + 1] } else { $null }
$operation = if (-not $hasTarget) { 'Malformed' }
elseif ([string]::IsNullOrEmpty($target)) { 'Delete' }
else { 'RenameOrMove' }
$advisory = [pscustomobject][ordered]@{
IsAdvisory = $false
NormalizedSource = ($source -replace '^(?:\*1)?\\\?\?\\', '')
Reason = if ($operation -eq 'Malformed') { 'MalformedPair' } else { 'NotEligibleForAdvisoryClassification' }
}
if ($operation -eq 'Delete' -and -not [string]::IsNullOrWhiteSpace($source)) {
$advisory = Test-PendingFileRenameAdvisoryCleanup -SourcePath $source
}
$records.Add([pscustomobject][ordered]@{
PairIndex = [int]($index / 2)
Source = $source
Target = $target
Operation = $operation
NormalizedSource = $advisory.NormalizedSource
AdvisoryCleanup = [bool]$advisory.IsAdvisory
ClassificationReason = [string]$advisory.Reason
}) | Out-Null
}
$advisoryCount = @($records | Where-Object AdvisoryCleanup).Count
$blockingCount = @($records | Where-Object { -not $_.AdvisoryCleanup }).Count
return [pscustomobject][ordered]@{
RawValueCount = $rawValues.Count
PairCount = $records.Count
Malformed = [bool]$malformed
AdvisoryOperationCount = $advisoryCount
BlockingOperationCount = $blockingCount
AdvisoryCleanupOnly = [bool]($records.Count -gt 0 -and -not $malformed -and $blockingCount -eq 0)
Records = $records.ToArray()
}
}
function Get-PendingRebootEvidence {
[CmdletBinding()]
[OutputType([pscustomobject])]
param()
$readErrors = New-Object 'System.Collections.Generic.List[string]'
$cbsPending = $false
try {
$cbsPending = Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
}
catch { $readErrors.Add('CBS: ' + $_.Exception.Message) }
$wuPending = $false
try {
$wuPending = Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
}
catch { $readErrors.Add('WU: ' + $_.Exception.Message) }
$pfroPresent = $false
$pfroEvidence = Convert-PendingFileRenameOperationsEvidence -Value $null
try {
$sessionManager = Get-RegistryKeySnapshot -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
$pfroValue = Get-NamedRegistryValue -Snapshot $sessionManager -Name 'PendingFileRenameOperations'
if ($null -ne $pfroValue) {
$pfroPresent = $true
$pfroEvidence = Convert-PendingFileRenameOperationsEvidence -Value $pfroValue
}
}
catch { $readErrors.Add('PFRO: ' + $_.Exception.Message) }
$pfroBlocking = [bool]($pfroPresent -and -not $pfroEvidence.AdvisoryCleanupOnly)
$blockingPending = [bool]($cbsPending -or $wuPending -or $pfroBlocking)
$advisoryPending = [bool](-not $blockingPending -and $pfroPresent -and $pfroEvidence.AdvisoryCleanupOnly)
$classification = if ($blockingPending) { 'Blocking' }
elseif ($advisoryPending) { 'Advisory' }
elseif ($readErrors.Count -gt 0) { 'Unknown' }
else { 'None' }
return [pscustomobject][ordered]@{
CollectedAtUtc = Get-UtcTimestamp
CbsRebootPending = $cbsPending
WindowsUpdateRebootPending = $wuPending
PendingFileRenamePresent = $pfroPresent
PendingFileRenameOperations = $pfroEvidence
ReadErrors = $readErrors.ToArray()
RebootPending = [bool]($blockingPending -or $advisoryPending)
BlockingRebootPending = $blockingPending
AdvisoryRebootPending = $advisoryPending
Classification = $classification
}
}
#endregion
#region Domain collectors (driver-deployment areas of this repository)
function Get-OperatingSystemEvidence {
[CmdletBinding()]
[OutputType([pscustomobject])]
param()
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$computer = Get-CimInstance -ClassName Win32_ComputerSystem
$cv = Get-RegistryKeySnapshot -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
$ubrValue = Get-NamedRegistryValue -Snapshot $cv -Name 'UBR'
return [pscustomobject][ordered]@{
CollectedAtUtc = Get-UtcTimestamp
ComputerName = [string]$env:COMPUTERNAME
Manufacturer = [string](Get-PropertyValue -InputObject $computer -Name 'Manufacturer')
Model = [string](Get-PropertyValue -InputObject $computer -Name 'Model')
OsCaption = [string]$os.Caption
OsVersion = [string]$os.Version
OsBuildNumber = [string]$os.BuildNumber
Ubr = if ($null -ne $ubrValue) { [int]$ubrValue } else { $null }
ProductName = [string](Get-NamedRegistryValue -Snapshot $cv -Name 'ProductName')
DisplayVersion = [string](Get-NamedRegistryValue -Snapshot $cv -Name 'DisplayVersion')
InstallationType = [string](Get-NamedRegistryValue -Snapshot $cv -Name 'InstallationType')
ProductType = [int]$os.ProductType
OsArchitecture = [string]$os.OSArchitecture
LastBootUpTimeUtc = $os.LastBootUpTime.ToUniversalTime().ToString('o')
InstallDateUtc = $os.InstallDate.ToUniversalTime().ToString('o')
PowerShellVersion = [string]$PSVersionTable.PSVersion
PowerShellEdition = [string](Get-PropertyValue -InputObject $PSVersionTable -Name 'PSEdition' -DefaultValue 'Desktop')
IsElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
CurrentVersionKey = $cv
}
}
function Get-PnpDeviceEvidence {
[CmdletBinding()]
[OutputType([pscustomobject])]
param()
$devices = @(Get-CimInstance -ClassName Win32_PnPEntity -ErrorAction Stop)
$records = New-Object 'System.Collections.Generic.List[object]'
$problems = New-Object 'System.Collections.Generic.List[object]'
$targeted = New-Object 'System.Collections.Generic.List[object]'
# HWID families this repository's four deploy scripts operate on:
# PCI\VEN_1022 (AMD), PCI\VEN_1002 (AMD/ATI display + HDMI audio),
# ACP\ (AMD audio co-processor), HDAUDIO\FUNC_01...VEN_1002,
# BTH\MS_BTHPAN (Microsoft Bluetooth PAN).
$targetPattern = '^(PCI\\VEN_1022|PCI\\VEN_1002|ACP\\|HDAUDIO\\FUNC_01&VEN_1002|BTH\\MS_BTHPAN)'
foreach ($device in $devices) {
$hardwareIds = @()
$rawIds = Get-PropertyValue -InputObject $device -Name 'HardwareID'
if ($null -ne $rawIds) { $hardwareIds = @($rawIds | ForEach-Object { [string]$_ }) }
$errorCode = Get-PropertyValue -InputObject $device -Name 'ConfigManagerErrorCode'
$record = [pscustomobject][ordered]@{
Name = [string](Get-PropertyValue -InputObject $device -Name 'Name')
PnpDeviceId = [string](Get-PropertyValue -InputObject $device -Name 'PNPDeviceID')
PnpClass = [string](Get-PropertyValue -InputObject $device -Name 'PNPClass')
Status = [string](Get-PropertyValue -InputObject $device -Name 'Status')
ConfigManagerErrorCode = if ($null -ne $errorCode) { [int]$errorCode } else { $null }
ConfigManagerErrorName = (Get-ConfigManagerErrorName -Code $errorCode)
Present = [bool](Get-PropertyValue -InputObject $device -Name 'Present' -DefaultValue $true)
HardwareIds = $hardwareIds
}
$records.Add($record) | Out-Null
if ($null -ne $record.ConfigManagerErrorCode -and $record.ConfigManagerErrorCode -ne 0) {
$problems.Add($record) | Out-Null
}
$isTargeted = $false
foreach ($hardwareId in $hardwareIds) {
if ($hardwareId -match $targetPattern) { $isTargeted = $true; break } # psa-disable-line PSA2003 -- $targetPattern is a non-null literal assigned above in this function
}
if (-not $isTargeted -and [string]$record.PnpDeviceId -match $targetPattern) { $isTargeted = $true } # psa-disable-line PSA2003 -- $targetPattern is a non-null literal assigned above in this function
if ($isTargeted) { $targeted.Add($record) | Out-Null }
}
return [pscustomobject][ordered]@{
CollectedAtUtc = Get-UtcTimestamp
DeviceCount = $records.Count
ProblemDeviceCount = $problems.Count
TargetedDeviceCount = $targeted.Count
TargetHardwareIdPattern = $targetPattern
ProblemDevices = $problems.ToArray()
TargetedDevices = $targeted.ToArray()
Devices = $records.ToArray()
}
}
function Get-ConfigManagerErrorName {
# CM_PROB_* name for a ConfigManagerErrorCode. Names are from the
# Windows CM_PROB_ constants and are stable across locales, which the
# localized Win32_PnPEntity.Status string is not.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter()]
$Code
)
if ($null -eq $Code) { return '' }
switch ([int]$Code) {
0 { 'OK' }
1 { 'CM_PROB_NOT_CONFIGURED - no driver configured for this device' }
3 { 'CM_PROB_OUT_OF_MEMORY - driver may be corrupted or memory is low' }
9 { 'CM_PROB_INVALID_DATA - device information is invalid' }
10 { 'CM_PROB_FAILED_START - device failed to start' }
12 { 'CM_PROB_NORMAL_CONFLICT - insufficient free resources' }
14 { 'CM_PROB_NEED_RESTART - restart required to take effect' }
18 { 'CM_PROB_REINSTALL - drivers must be reinstalled' }
19 { 'CM_PROB_REGISTRY - registry configuration is damaged' }
21 { 'CM_PROB_WILL_BE_REMOVED - device is being removed' }
22 { 'CM_PROB_DISABLED - device is disabled' }
24 { 'CM_PROB_DEVICE_NOT_THERE - device is not present or is failing' }
28 { 'CM_PROB_FAILED_INSTALL - drivers are not installed for this device' }
29 { 'CM_PROB_HARDWARE_DISABLED - disabled by firmware' }
31 { 'CM_PROB_FAILED_ADD - Windows cannot load the required drivers' }
32 { 'CM_PROB_DISABLED_SERVICE - start type of the driver service is disabled' }
35 { 'CM_PROB_HELD_FOR_EJECT - firmware does not include enough information' }
37 { 'CM_PROB_DRIVER_FAILED_PRIOR_UNLOAD - driver returned failure on unload' }
38 { 'CM_PROB_DRIVER_BLOCKED - a previous instance is still in memory' }
39 { 'CM_PROB_FAILED_DRIVER_LOAD - driver is corrupted, missing, or rejected' }
40 { 'CM_PROB_INVALID_DATA - registry service key information is invalid' }
41 { 'CM_PROB_FAILED_POST_START - driver loaded but no PnP device was found' }
43 { 'CM_PROB_HALTED - the device reported a problem and was stopped' }
45 { 'CM_PROB_PHANTOM - device is not currently connected' }
51 { 'CM_PROB_WAITING_ON_DEPENDENCY - waiting on another device or service' }
52 { 'CM_PROB_UNSIGNED_DRIVER - cannot verify the digital signature' }
54 { 'CM_PROB_DEVICE_RESET - device is failing or being reset' }
default { ('CM_PROB (code {0}) - see Device Manager for detail' -f [int]$Code) }
}
}
function Get-DriverLoadStatusName {
# NTSTATUS values that appear beside CM_PROB codes in setupapi.dev.log.
# The signature-related ones are called out explicitly because
# distinguishing "kernel rejected the signature" from "the driver does
# not fit this OS build" is the first fork in any load-failure triage,
# and the two look identical at the Device Manager level.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter()]
[string]$Status
)
if ([string]::IsNullOrWhiteSpace($Status)) { return '' }
switch ($Status.ToLowerInvariant().Replace('0x', '')) {
'c0000428' { 'STATUS_INVALID_IMAGE_HASH - SIGNATURE: the kernel refused the image signature' }
'c0000603' { 'STATUS_IMAGE_CERT_REVOKED - SIGNATURE: the signing certificate is revoked' }
'c000036b' { 'STATUS_IMAGE_CERT_EXPIRED - SIGNATURE: the signing certificate has expired' }
'c0000262' { 'STATUS_DRIVER_ORDINAL_NOT_FOUND - NOT a signature problem: the driver imports an ordinal this OS build does not export' }
'c0000263' { 'STATUS_DRIVER_ENTRYPOINT_NOT_FOUND - NOT a signature problem: the driver imports an entry point this OS build does not export' }
'c0000365' { 'STATUS_FAILED_DRIVER_ENTRY - the driver''s DriverEntry returned failure' }
'c000009c' { 'STATUS_DEVICE_DATA_ERROR - device data error' }
'c0000490' { 'STATUS_DEVICE_HARDWARE_ERROR - device reported a hardware error' }
'c0000493' { 'STATUS_DEVICE_NOT_CONNECTED - the device was not connected when evaluated' }
'c0000001' { 'STATUS_UNSUCCESSFUL' }
default { ('NTSTATUS {0} - undecoded' -f $Status) }
}
}
function Get-SetupApiFailureEvidence {
# Extract failure records from setupapi.dev.log.
#
# setupapi.dev.log is already copied verbatim into the bundle, but a
# multi-megabyte verbatim copy is not evidence anyone reads under
# pressure. This pulls out the parts that matter: per-device-install
# sections that ended in failure, the SetupAPI error code, any
# "Binary '<path>' for service '<name>' is not present" line (a missing
# OS component the device's own INF requires), and any CM problem plus
# NT status pair.
#
# Parsing keys off tokens that do not change with the display language.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter()]
[string]$LogPath,
[Parameter()]
[int]$MaxSections = 40
)
$result = [pscustomobject][ordered]@{
CollectedAtUtc = Get-UtcTimestamp
LogPath = [string]$LogPath
LogPresent = $false
SectionsScanned = 0
FailureSections = @()
MissingServiceBinaries = @()
ParseError = ''
}
if ([string]::IsNullOrWhiteSpace($LogPath) -or -not (Test-Path -LiteralPath $LogPath)) {
return $result
}
$result.LogPresent = $true
try {
$lines = @(Get-Content -LiteralPath $LogPath -ErrorAction Stop)
} catch {
$result.ParseError = $_.Exception.Message
return $result
}
$sections = New-Object 'System.Collections.Generic.List[object]'
$missing = New-Object 'System.Collections.Generic.List[object]'
$startIndexes = New-Object 'System.Collections.Generic.List[int]'
for ($i = 0; $i -lt $lines.Count; $i++) {
# Substring test, not -like: in a PowerShell wildcard '[' opens a
# character class, so '>>>*[Device Install*' is an unterminated
# class and throws WildcardPatternException on the first line it
# is applied to. .Contains carries no pattern semantics at all,
# which is what this test actually wants.
$lineText = [string]$lines[$i]
if ($lineText.StartsWith('>>>') -and $lineText.Contains('[Device Install')) { $startIndexes.Add($i) | Out-Null }
}
$result.SectionsScanned = $startIndexes.Count
foreach ($start in $startIndexes) {
$end = $lines.Count - 1
foreach ($candidate in $startIndexes) {
if ($candidate -gt $start) { $end = $candidate - 1; break }
}
$header = [string]$lines[$start]
$timestamp = ''
$errors = New-Object 'System.Collections.Generic.List[string]'
$problem = ''
$problemStatus = ''
$failed = $false
for ($j = $start; $j -le $end; $j++) {
$line = [string]$lines[$j]
if ($line.StartsWith('>>>') -and $line.Contains('Section start')) {
$timestamp = ($line -split 'Section start')[-1].Trim()
}
if ($line -match 'Error 0x[0-9a-fA-F]+') {
$failed = $true
$token = ([regex]::Match($line, 'Error 0x[0-9a-fA-F]+')).Value
if (-not $errors.Contains($token)) { $errors.Add($token) | Out-Null }
}
if ($line -match "Binary '([^']+)' for service '([^']+)' is not present") {
$failed = $true
$binary = $Matches[1]
$service = $Matches[2]
$missing.Add([pscustomobject][ordered]@{
ServiceName = [string]$service
ExpectedBinary = [string]$binary
BinaryExists = (Test-Path -LiteralPath ([string]$binary))
SeenInSection = $header
}) | Out-Null
}
if ($line -match 'Problem: 0x([0-9a-fA-F]+) \(0x([0-9a-fA-F]+)\)') {
$problem = [string]([Convert]::ToInt32($Matches[1], 16))
$problemStatus = '0x' + $Matches[2]
}
if ($line.Contains('[Exit status: FAILURE')) { $failed = $true }
# A '!!!' marker is setupapi's own failure flag and is the ONLY
# failure signal some sections carry: a device that installs
# cleanly but will not START logs '!!! Device not started' with a
# CM problem code and still exits SUCCESS. Those sections are the
# load failures - exactly what this extract is for - and keying
# only off 'Error 0x' and the exit status silently drops them.
if ($line.StartsWith('!!!')) { $failed = $true }
}
if (-not $failed) { continue }
$sections.Add([pscustomobject][ordered]@{
Header = $header
SectionStart = $timestamp
SetupApiErrors = $errors.ToArray()
ConfigManagerErrorCode = $problem
ConfigManagerErrorName = (Get-ConfigManagerErrorName -Code $(if ($problem -ne '') { [int]$problem } else { $null }))
DriverLoadStatus = $problemStatus
DriverLoadStatusName = (Get-DriverLoadStatusName -Status $problemStatus)
}) | Out-Null
}
$keep = @($sections.ToArray())
if ($keep.Count -gt $MaxSections) {
$keep = @($keep[($keep.Count - $MaxSections)..($keep.Count - 1)])
}
$result.FailureSections = $keep
$result.MissingServiceBinaries = $missing.ToArray()
return $result
}
function Get-DeviceLoadDiagnosticEvidence {
# Per-problem-device diagnostics: what is bound, what service backs it,
# and whether that service's binary is actually on disk.
#
# The last item is the one the field run needed and did not have. A
# device install can fail because the INF declares a service whose
# binary ships with an OS feature that is not installed on this SKU -
# a state that is invisible in the device record and obvious the moment
# you test the ImagePath.
[CmdletBinding()]
[OutputType([pscustomobject])]
param(
[Parameter()]
$PnpEvidence,
[Parameter()]
[string]$SetupApiLogPath
)
$records = New-Object 'System.Collections.Generic.List[object]'
$signedDrivers = @{}
try {
foreach ($d in @(Get-CimInstance -ClassName Win32_PnPSignedDriver -ErrorAction Stop)) {
$id = [string](Get-PropertyValue -InputObject $d -Name 'DeviceID')
if (-not [string]::IsNullOrWhiteSpace($id) -and -not $signedDrivers.ContainsKey($id)) {
$signedDrivers[$id] = $d
}
}
} catch {
$signedDrivers = @{}
}
$problemDevices = @()
if ($null -ne $PnpEvidence -and $PnpEvidence.PSObject.Properties['ProblemDevices']) {
$problemDevices = @($PnpEvidence.ProblemDevices)
}
foreach ($device in $problemDevices) {
$id = [string]$device.PnpDeviceId
$serviceName = ''
$infName = ''
$driverVersion = ''
$driverProvider = ''
if ($signedDrivers.ContainsKey($id)) {
$sd = $signedDrivers[$id]
$infName = [string](Get-PropertyValue -InputObject $sd -Name 'InfName')
$driverVersion = [string](Get-PropertyValue -InputObject $sd -Name 'DriverVersion')
$driverProvider = [string](Get-PropertyValue -InputObject $sd -Name 'DriverProviderName')
}
# The device's service name lives under the device's Enum key.
# Resolve the device's service via the registry snapshot helper.
# Get-NamedRegistryValue takes a SNAPSHOT produced by
# Get-RegistryKeySnapshot, not a path - passing -Path binds nothing
# and throws ParameterBindingException at every problem device.
$imagePath = ''
$imagePathResolved = ''
$imagePathExists = $null
$serviceStartType = ''
try {
$enumSnapshot = Get-RegistryKeySnapshot -Path ('HKLM:\SYSTEM\CurrentControlSet\Enum\' + $id)
$serviceName = [string](Get-NamedRegistryValue -Snapshot $enumSnapshot -Name 'Service' -DefaultValue '')
} catch {
$serviceName = ''
}
if (-not [string]::IsNullOrWhiteSpace($serviceName)) {
try {
$svcSnapshot = Get-RegistryKeySnapshot -Path ('HKLM:\SYSTEM\CurrentControlSet\Services\' + $serviceName)
$imagePath = [string](Get-NamedRegistryValue -Snapshot $svcSnapshot -Name 'ImagePath' -DefaultValue '')
$startValue = Get-NamedRegistryValue -Snapshot $svcSnapshot -Name 'Start'
if ($null -ne $startValue) { $serviceStartType = [string]$startValue }
} catch {
$imagePath = ''
}
}
if (-not [string]::IsNullOrWhiteSpace($imagePath)) {
$candidate = Resolve-ServiceImagePath -ImagePath $imagePath
$imagePathResolved = $candidate
try {
$imagePathExists = [bool](Test-Path -LiteralPath $candidate)
} catch {
$imagePathExists = $null
}
}
$records.Add([pscustomobject][ordered]@{
Name = [string]$device.Name
PnpDeviceId = $id
ConfigManagerErrorCode = $device.ConfigManagerErrorCode
ConfigManagerErrorName = (Get-ConfigManagerErrorName -Code $device.ConfigManagerErrorCode)
BoundInfName = $infName
DriverVersion = $driverVersion
DriverProvider = $driverProvider
ServiceName = $serviceName
ServiceStartType = $serviceStartType
ServiceImagePath = $imagePath
ServiceImagePathResolved = $imagePathResolved
ServiceBinaryPresent = $imagePathExists
HardwareIds = @($device.HardwareIds)
}) | Out-Null
}
$setupApi = Get-SetupApiFailureEvidence -LogPath $SetupApiLogPath
$missingBinaryCount = 0
foreach ($r in $records) {
if ($r.ServiceBinaryPresent -eq $false) { $missingBinaryCount++ }
}
$signatureRelated = 0
foreach ($s in @($setupApi.FailureSections)) {
if ([string]$s.DriverLoadStatusName -like '*SIGNATURE:*') { $signatureRelated++ }
}
return [pscustomobject][ordered]@{
CollectedAtUtc = Get-UtcTimestamp
ProblemDeviceCount = $records.Count
MissingServiceBinaryCount = $missingBinaryCount
SignatureRelatedFailureCount = $signatureRelated
ProblemDevices = $records.ToArray()
SetupApi = $setupApi
}
}
function Resolve-ServiceImagePath {
# Turn a service ImagePath registry value into a testable filesystem path.
#
# ImagePath is stored in several shapes and the differences are not
# cosmetic - a caller that skips this normalisation silently concludes
# that every driver binary is missing:
# \SystemRoot\System32\drivers\x.sys (kernel drivers, most common)
# \??\C:\path\x.sys (NT object-manager prefix)
# system32\drivers\x.sys (relative, no leading separator)
# "C:\path\svc.exe" -k netsvcs (user-mode services, quoted + args)
#
# A regression this function exists to prevent: the earlier inline
# version used the regex '^\SystemRoot', in which \S is the
# non-whitespace character class, so it never matched anything and the
# \SystemRoot form was returned untouched.
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter()]
[AllowEmptyString()]
[string]$ImagePath
)
if ([string]::IsNullOrWhiteSpace($ImagePath)) { return '' }
$value = $ImagePath.Trim()
# Plain concatenation rather than Join-Path: Join-Path resolves the
# drive qualifier, which makes this function untestable anywhere but a
# Windows host with that drive present. The separator handling here is
# trivial and the testability is not.
$root = [string]$env:SystemRoot
if ([string]::IsNullOrWhiteSpace($root)) { $root = 'C:\Windows' }
$root = $root.TrimEnd('\')
# User-mode services quote the executable and append arguments. Take the
# quoted span when present, otherwise everything up to the first space
# that is followed by a switch-looking token.
if ($value.StartsWith('"')) {
$closing = $value.IndexOf('"', 1)
if ($closing -gt 1) { $value = $value.Substring(1, $closing - 1) }
} elseif ($value -match '^(?<path>\S+\.(exe|sys|dll))\s') {
$value = $Matches['path']
}
if ($value.StartsWith('\??\')) {
$value = $value.Substring(4)
} elseif ($value -match '^\\SystemRoot\\') {
$value = $root + '\' + $value.Substring('\SystemRoot\'.Length)
} elseif ($value.StartsWith('\')) {
# Any other leading-separator form is relative to the system root.
$value = $root + '\' + $value.TrimStart('\')
} elseif ($value -notmatch '^[A-Za-z]:\\') {
$value = $root + '\' + $value
}
return $value
}
function Get-ServiceConfigurationEvidence {
# Complete Windows service configuration, every service, no filter.
#
# WHY the whole set and not just driver services: the failure that
# motivated this stage was a Windows Server DEFAULT CONFIGURATION issue -
# an inbox wireless component whose binary is not staged on Server SKUs,
# which broke an unrelated third-party adapter during a driver install.
# Narrowing the census to driver services, or to this project's own
# services, would have recorded everything except the thing that
# mattered. The evidence bundle is read by people and by language models
# trying to explain a host they cannot log into; a partial census invites
# confident wrong answers about what is present.
#
# Cost is bounded: a Server install carries a few hundred services, and
# the record per service is small.
[CmdletBinding()]
[OutputType([pscustomobject])]
param()
$records = New-Object 'System.Collections.Generic.List[object]'
$missingBinaries = New-Object 'System.Collections.Generic.List[object]'
$collectionErrors = New-Object 'System.Collections.Generic.List[string]'
$services = @()
try {
$services = @(Get-CimInstance -ClassName Win32_Service -ErrorAction Stop)
} catch {
$collectionErrors.Add(('Win32_Service query failed: {0}' -f $_.Exception.Message)) | Out-Null
}
# Win32_Service covers user-mode services and drivers registered as
# services, but NOT every kernel driver: those live in
# Win32_SystemDriver. Both are needed for a complete picture, and the
# missing-binary case that motivated this stage is a kernel driver.
$systemDrivers = @()
try {
$systemDrivers = @(Get-CimInstance -ClassName Win32_SystemDriver -ErrorAction Stop)
} catch {
$collectionErrors.Add(('Win32_SystemDriver query failed: {0}' -f $_.Exception.Message)) | Out-Null
}