Repository navigation
Expand file tree
/
Copy pathUpdate-WSUSComputerOperatingSystems.ps1
More file actions
865 lines (841 loc) · 29.2 KB
/
Copy pathUpdate-WSUSComputerOperatingSystems.ps1
File metadata and controls
865 lines (841 loc) · 29.2 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
# Update tbComputerTargetDetail for WSUS to add more details in OSDescription field (based on https://www.wsus.de/windows-editionen-anzeigen/)
# See also https://server-essentials.com/support/windows-10-vista-wsus-not-updating
# See also https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wusp/5f216289-0876-4dc3-ad85-e1d61a9e7ce1#Appendix_A_13
#Requires -Version 5.1
<#
.SYNOPSIS
Fix WSUS OS descriptions once, or continuously using SQL Query Notifications.
.DESCRIPTION
Builds on Borgquite/Update-WSUSComputerOperatingSystems (GPL-3.0)
and retains its OS catalog. This fork adds event-driven monitoring via
SqlDependency, automatic SQL reconnection and configurable log storage.
No SqlServer module or other external PowerShell dependency is needed.
.EXAMPLE
.\Update-WSUSComputerOperatingSystems.ps1
.EXAMPLE
.\Update-WSUSComputerOperatingSystems.ps1 -AsService
.EXAMPLE
.\Update-WSUSComputerOperatingSystems.ps1 -AsService -DurationMinutes 60
.EXAMPLE
.\Update-WSUSComputerOperatingSystems.ps1 -AsService -LogDirectory '\\server\share\_Logs'
#>
[CmdletBinding()]
param(
[Parameter()][string]$SQLServerInstance = '\\.\pipe\MICROSOFT##WID\tsql\query',
[Parameter()][ValidateSet('Optional','Mandatory','True','False')][string]$Encrypt = 'Optional',
[Parameter()][switch]$AsService,
[Parameter()][ValidateRange(0,43200)][int]$DurationMinutes = 0,
[Parameter()][string]$LogDirectory
)
$ErrorActionPreference = 'Stop'
if (-not $AsService -and $PSBoundParameters.ContainsKey('DurationMinutes')) {
throw '-DurationMinutes requires -AsService.'
}
Add-Type -AssemblyName System.Data
# OS catalog from Borgquite/Update-WSUSComputerOperatingSystems (GPL-3.0).
# Original structured PowerShell data, retained to simplify upstream updates.
# https://github.com/Borgquite/Update-WSUSComputerOperatingSystems
$ClientProductVersions = @(
# Based on https://learn.microsoft.com/en-us/windows/release-health/release-information
@{
ProductVersion = ' 8'
OSMajorVersion = 6
OSMinorVersion = 2
OSBuildNumber = 9200
}
@{
ProductVersion = ' 8.1'
OSMajorVersion = 6
OSMinorVersion = 3
OSBuildNumber = 9600
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1507'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 10240
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1511'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 10586
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1607'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 14393
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1703'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 15063
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1709'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 16299
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1803'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 17134
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1809'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 17763
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1903'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 18362
}
@{
ProductVersion = ' 10'
ProductRelease = ' 1909'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 18363
}
@{
ProductVersion = ' 10'
ProductRelease = ' 2004'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19041
}
@{
ProductVersion = ' 10'
ProductRelease = ' 20H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19042
}
@{
ProductVersion = ' 10'
ProductRelease = ' 21H1'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19043
}
@{
ProductVersion = ' 10'
ProductRelease = ' 21H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19044
}
@{
ProductVersion = ' 10'
ProductRelease = ' 22H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19045
}
@{
ProductVersion = ' 11'
ProductRelease = ' 21H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 22000
}
@{
ProductVersion = ' 11'
ProductRelease = ' 22H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 22621
}
@{
ProductVersion = ' 11'
ProductRelease = ' 23H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 22631
}
@{
ProductVersion = ' 11'
ProductRelease = ' 24H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 26100
}
@{
ProductVersion = ' 11'
ProductRelease = ' 25H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 26200
}
@{
ProductVersion = ' 11'
ProductRelease = ' 26H1'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 28000
}
@{
ProductVersion = ' 11'
ProductRelease = ' 26H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 26300
}
)
$ServerProductVersions = @(
# Based on https://learn.microsoft.com/en-us/windows/release-health/windows-server-release-info
@{
ProductVersion = ' 2012'
OSMajorVersion = 6
OSMinorVersion = 2
OSBuildNumber = 9200
}
@{
ProductVersion = ' 2012 R2'
OSMajorVersion = 6
OSMinorVersion = 3
OSBuildNumber = 9600
}
@{
ProductVersion = ' 2016'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 14393
}
@{
ProductVersion = ', version 1709'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 16299
}
@{
ProductVersion = ', version 1803'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 17134
}
@{
ProductVersion = ' 2019'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 17763
}
@{
ProductVersion = ', version 1903'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 18362
}
@{
ProductVersion = ', version 1909'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 18363
}
@{
ProductVersion = ', version 2004'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19041
}
@{
ProductVersion = ', version 20H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 19042
}
@{
ProductVersion = ' 2022'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 20348
}
@{
ProductVersion = ', version 23H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 25398
}
@{
ProductVersion = ' 2025'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 26100
}
)
$AzureStackHCIProductVersions = @(
# Based on https://betawiki.net/wiki/Azure_Stack_HCI
@{
ProductVersion = ', version 20H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 17784
}
@{
ProductVersion = ', version 21H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 20348
}
@{
ProductVersion = ', version 22H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 20349
}
@{
ProductVersion = ', version 23H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 25398
}
@{
ProductVersion = ', version 24H2'
OSMajorVersion = 10
OSMinorVersion = 0
OSBuildNumber = 26100
}
)
$OSDescriptions = @(
@{
ProductName = 'Windows'
ProductVersions = $ClientProductVersions
ProductTypes = @(
# Based on https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem
# Based on https://learn.microsoft.com/en-us/mem/intune/fundamentals/filters-device-properties
# Based on https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getproductinfo
# Based on https://betawiki.net/wiki/List_of_Windows_product_types
# LTSC editions are omitted to preserve client-reported release-year names.
@{
ProductEdition = ' S'
NewProductTypes = @(178)
}
@{
ProductEdition = ' S N'
NewProductTypes = @(179)
}
@{
ProductEdition = ' Pro N'
NewProductTypes = @(49)
}
@{
ProductEdition = ' SE'
NewProductTypes = @(203)
}
@{
ProductEdition = ' SE N'
NewProductTypes = @(202)
}
@{
ProductEdition = ' Home'
NewProductTypes = @(101, 111)
}
@{
ProductEdition = ' Home China'
NewProductTypes = @(99)
}
@{
ProductEdition = ' Home N'
NewProductTypes = @(98)
}
@{
ProductEdition = ' Home Single Language'
NewProductTypes = @(100)
}
@{
ProductEdition = ' Education'
NewProductTypes = @(121)
}
@{
ProductEdition = ' Education N'
NewProductTypes = @(122)
}
@{
ProductEdition = ' Enterprise'
NewProductTypes = @(4)
}
@{
ProductEdition = ' Enterprise Evaluation'
NewProductTypes = @(72)
}
@{
ProductEdition = ' Enterprise G'
NewProductTypes = @(171)
}
@{
ProductEdition = ' Enterprise G N'
NewProductTypes = @(172)
}
@{
ProductEdition = ' Enterprise N'
NewProductTypes = @(27)
}
@{
ProductEdition = ' Enterprise N Evaluation'
NewProductTypes = @(84)
}
@{
ProductEdition = ' Holographic'
NewProductTypes = @(135)
}
@{
ProductEdition = ' Holographic for Business'
NewProductTypes = @(136)
}
@{
ProductEdition = ' IoT Core'
NewProductTypes = @(123)
}
@{
ProductEdition = ' IoT Core Commercial'
NewProductTypes = @(131)
}
@{
ProductEdition = ' IoT Enterprise'
NewProductTypes = @(188)
}
@{
ProductEdition = ' Mobile'
NewProductTypes = @(104)
}
@{
ProductEdition = ' Mobile Enterprise'
NewProductTypes = @(133)
}
@{
ProductEdition = ' Team'
NewProductTypes = @(119)
}
@{
ProductEdition = ' Pro'
NewProductTypes = @(48)
}
@{
ProductEdition = ' Pro Education'
NewProductTypes = @(164)
}
@{
ProductEdition = ' Pro Education N'
NewProductTypes = @(165)
}
@{
ProductEdition = ' Pro for Workstations'
NewProductTypes = @(161)
}
@{
ProductEdition = ' Pro for Workstations N'
NewProductTypes = @(162)
}
@{
ProductEdition = ' Pro China'
NewProductTypes = @(139)
}
@{
ProductEdition = ' Pro Single Language'
NewProductTypes = @(138)
}
@{
ProductEdition = ' Enterprise multi-session'
NewProductTypes = @(175)
}
)
}
@{
ProductName = 'Windows RT'
ProductVersions = $ClientProductVersions
ProductTypes = @(
@{
ProductEdition = ''
NewProductTypes = @(97)
}
)
}
@{
ProductName = 'Windows Server'
ProductVersions = $ServerProductVersions
ProductTypes = @(
# Based on https://learn.microsoft.com/en-us/dotnet/api/microsoft.powershell.commands.operatingsystemsku
@{
ProductEdition = ' Standard'
NewProductTypes = @(7, 13)
}
@{
ProductEdition = ' Standard Evaluation'
NewProductTypes = @(79, 160)
}
@{
ProductEdition = ' Datacenter'
NewProductTypes = @(8, 12)
}
@{
ProductEdition = ' Datacenter Evaluation'
NewProductTypes = @(80, 159)
}
@{
ProductEdition = ' Datacenter: Azure Edition'
NewProductTypes = @(407)
}
@{
ProductEdition = ' Datacenter: Azure Edition Core'
NewProductTypes = @(408)
}
@{
ProductEdition = ' Foundation'
NewProductTypes = @(33)
}
@{
ProductEdition = ' Essentials'
NewProductTypes = @(50)
}
)
}
@{
ProductName = 'Microsoft Hyper-V Server'
ProductVersions = $ServerProductVersions
ProductTypes = @(
@{
ProductEdition = ''
NewProductTypes = @(42)
}
)
}
@{
ProductName = 'Microsoft Azure Stack HCI'
ProductVersions = $AzureStackHCIProductVersions
ProductTypes = @(
@{
ProductEdition = ''
NewProductTypes = @(406)
}
)
}
)
function Get-OsKey($Major, $Minor, $Build, $ProductType) {
return (@([string]$Major, [string]$Minor, [string]$Build, [string]$ProductType) -join '|')
}
function New-NameCatalog {
$lookup = @{}
foreach ($OSDescription in $OSDescriptions) {
foreach ($ProductVersion in $OSDescription.ProductVersions) {
foreach ($ProductType in $OSDescription.ProductTypes) {
foreach ($NewProductType in $ProductType.NewProductTypes) {
$key = Get-OsKey $ProductVersion.OSMajorVersion $ProductVersion.OSMinorVersion $ProductVersion.OSBuildNumber $NewProductType
$description = "$($OSDescription.ProductName)$($ProductVersion.ProductVersion)$($ProductType.ProductEdition)$($ProductVersion.ProductRelease)"
if ($lookup.ContainsKey($key) -and $lookup[$key] -cne $description) {
throw "Conflicting OS catalog entry: $key"
}
$lookup[$key] = $description
}
}
}
}
if ($lookup.Count -eq 0) { throw 'OS name catalog is empty.' }
return $lookup
}
$builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
if ($SQLServerInstance.StartsWith('\\.\pipe\', [StringComparison]::OrdinalIgnoreCase)) {
$builder['Data Source'] = 'np:' + $SQLServerInstance
} else {
$builder['Data Source'] = $SQLServerInstance
}
$builder['Initial Catalog'] = 'SUSDB'
$builder['Integrated Security'] = $true
$builder['Application Name'] = 'WSUS-OS-EventFix'
# System.Data.SqlClient expects a boolean. Mandatory requires a trusted SQL TLS certificate.
$builder['Encrypt'] = ($Encrypt -eq 'Mandatory' -or $Encrypt -eq 'True')
$connectionString = $builder.ConnectionString
$eventName = 'WSUS.OS.EventFix.Change'
# With no -LogDirectory (or an empty one), keep the original local log location.
$logDirectory = if ([string]::IsNullOrWhiteSpace($LogDirectory)) { $PSScriptRoot } else { $LogDirectory.Trim().Trim('"') }
$logFile = Join-Path $logDirectory 'Update-WSUSComputerOperatingSystems.log'
$localErrorFile = Join-Path $PSScriptRoot 'Update-WSUSComputerOperatingSystems_errors.log'
$separateLocalErrors = -not ([IO.Path]::GetFullPath($logFile)).Equals(
[IO.Path]::GetFullPath((Join-Path $PSScriptRoot 'Update-WSUSComputerOperatingSystems.log')),
[StringComparison]::OrdinalIgnoreCase)
$logRunSeparated = $false
$localErrorsSeparated = $false
$endTime = if ($AsService -and $DurationMinutes -gt 0) { (Get-Date).AddMinutes($DurationMinutes) } else { $null }
$listenerStarted = $false
function Write-LocalError {
param([Parameter(Mandatory = $true)][string]$Line)
try {
if (-not $script:localErrorsSeparated) {
if ((Test-Path -LiteralPath $localErrorFile -PathType Leaf -ErrorAction Stop) -and
(Get-Item -LiteralPath $localErrorFile -ErrorAction Stop).Length -gt 0) {
Add-Content -LiteralPath $localErrorFile -Value '' -Encoding UTF8 -ErrorAction Stop
}
$script:localErrorsSeparated = $true
}
Add-Content -LiteralPath $localErrorFile -Value $Line -Encoding UTF8 -ErrorAction Stop
} catch {
Write-Warning ('Unable to write the local error log: ' + $_.Exception.Message)
}
}
function Write-Log {
param(
[Parameter(Mandatory = $true)][string]$Message,
[ValidateSet('INFO', 'WARNING', 'ERROR')][string]$Level = 'INFO'
)
$line = '{0} [{1}] {2}' -f (Get-Date -Format 'dd.MM.yyyy HH:mm:ss.fff'), $Level, $Message
Write-Host $line
# Keep warnings and errors locally even when the main log is on a share.
if ($Level -ne 'INFO' -and $separateLocalErrors) { Write-LocalError $line }
try {
if (-not $script:logRunSeparated) {
if (-not (Test-Path -LiteralPath $logDirectory -PathType Container -ErrorAction Stop)) {
New-Item -ItemType Directory -Path $logDirectory -Force -ErrorAction Stop | Out-Null
}
if ((Test-Path -LiteralPath $logFile -PathType Leaf -ErrorAction Stop) -and
(Get-Item -LiteralPath $logFile -ErrorAction Stop).Length -gt 0) {
Add-Content -LiteralPath $logFile -Value '' -Encoding UTF8 -ErrorAction Stop
}
$script:logRunSeparated = $true
}
Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8 -ErrorAction Stop
} catch {
$diagnostic = '{0} [ERROR] Cannot write log {1}: {2}; entry: {3}' -f
(Get-Date -Format 'dd.MM.yyyy HH:mm:ss.fff'), $logFile, $_.Exception.Message, $line
Write-Warning $diagnostic
# Only errors and failures are written next to the script, not a copy of the whole log.
if (-not ($Level -ne 'INFO' -and $separateLocalErrors)) { Write-LocalError $line }
Write-LocalError $diagnostic
}
}
function Set-SqlNotificationOptions([System.Data.SqlClient.SqlConnection]$Connection) {
$cmd = $Connection.CreateCommand()
try {
$cmd.CommandText = 'SET ANSI_NULLS ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS ON; SET CONCAT_NULL_YIELDS_NULL ON; SET QUOTED_IDENTIFIER ON; SET ARITHABORT ON; SET NUMERIC_ROUNDABORT OFF;'
[void]$cmd.ExecuteNonQuery()
} finally { $cmd.Dispose() }
}
function Get-Snapshot([bool]$Subscribe = $false) {
$connection = [System.Data.SqlClient.SqlConnection]::new($connectionString)
$command = $null
$reader = $null
try {
$connection.Open()
if ($Subscribe) { Set-SqlNotificationOptions $connection }
$command = $connection.CreateCommand()
$command.CommandTimeout = 30
$command.CommandText = 'SELECT [TargetID], [OSDescription], [OSBuildNumber], [OSMajorVersion], [OSMinorVersion], [NewProductType] FROM [dbo].[tbComputerTargetDetail]'
if ($Subscribe) {
$dependency = [System.Data.SqlClient.SqlDependency]::new($command)
[void](Register-ObjectEvent -InputObject $dependency -EventName OnChange -SourceIdentifier $eventName)
}
$rows = @{}
$reader = $command.ExecuteReader()
while ($reader.Read()) {
$id = [string]$reader.GetValue(0)
$rows[$id] = [pscustomobject]@{
Id = $id
Description = if ($reader.IsDBNull(1)) { $null } else { [string]$reader.GetValue(1) }
Build = if ($reader.IsDBNull(2)) { $null } else { $reader.GetValue(2) }
Major = if ($reader.IsDBNull(3)) { $null } else { $reader.GetValue(3) }
Minor = if ($reader.IsDBNull(4)) { $null } else { $reader.GetValue(4) }
Type = if ($reader.IsDBNull(5)) { $null } else { $reader.GetValue(5) }
}
}
return $rows
}
catch {
if ($Subscribe) { Clear-Notifications }
throw
}
finally {
if ($null -ne $reader) { $reader.Dispose() }
if ($null -ne $command) { $command.Dispose() }
$connection.Dispose()
}
}
function Get-ComputerNames {
$names = @{}
$connection = [System.Data.SqlClient.SqlConnection]::new($connectionString)
$command = $null
$reader = $null
try {
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = 'SELECT [TargetID], [FullDomainName] FROM [dbo].[tbComputerTarget]'
$reader = $command.ExecuteReader()
while ($reader.Read()) {
$id = [string]$reader.GetValue(0)
$names[$id] = if ($reader.IsDBNull(1)) { $id } else { [string]$reader.GetValue(1) }
}
}
finally {
if ($null -ne $reader) { $reader.Dispose() }
if ($null -ne $command) { $command.Dispose() }
$connection.Dispose()
}
return $names
}
function Set-DescriptionById($Row, [string]$DesiredDescription) {
$connection = [System.Data.SqlClient.SqlConnection]::new($connectionString)
$cmd = $null
try {
$connection.Open()
$cmd = $connection.CreateCommand()
$cmd.CommandTimeout = 30
$cmd.CommandText = @'
UPDATE [dbo].[tbComputerTargetDetail]
SET [OSDescription] = @Description
WHERE [TargetID] = @TargetID
AND [OSMajorVersion] = @Major
AND [OSMinorVersion] = @Minor
AND [OSBuildNumber] = @Build
AND [NewProductType] = @Type
AND ([OSDescription] IS NULL OR [OSDescription] <> @Description)
'@
[void]$cmd.Parameters.Add('@Description', [System.Data.SqlDbType]::NVarChar, 256)
$cmd.Parameters['@Description'].Value = $DesiredDescription
[void]$cmd.Parameters.Add('@TargetID', [System.Data.SqlDbType]::Int)
$cmd.Parameters['@TargetID'].Value = [int]$Row.Id
foreach ($part in @(@('Major',$Row.Major), @('Minor',$Row.Minor),
@('Build',$Row.Build), @('Type',$Row.Type))) {
$parameterName = '@' + $part[0]
[void]$cmd.Parameters.Add($parameterName, [System.Data.SqlDbType]::Int)
$cmd.Parameters[$parameterName].Value = [int]$part[1]
}
return [int]$cmd.ExecuteNonQuery()
}
finally {
if ($null -ne $cmd) { $cmd.Dispose() }
$connection.Dispose()
}
}
function Process-Changes([hashtable]$Before, [hashtable]$After, [hashtable]$Lookup, [string]$InitialReason = 'ADDED') {
$affected = [System.Collections.Generic.List[object]]::new()
foreach ($id in $After.Keys) {
$row = $After[$id]
if (-not $Before.ContainsKey($id)) {
$affected.Add([pscustomobject]@{ Row = $row; Reason = $InitialReason })
continue
}
$old = $Before[$id]
if ($old.Description -cne $row.Description -or $old.Build -ne $row.Build -or
$old.Major -ne $row.Major -or $old.Minor -ne $row.Minor -or $old.Type -ne $row.Type) {
$affected.Add([pscustomobject]@{ Row = $row; Reason = 'CHANGED' })
}
}
$wrong = [System.Collections.Generic.List[object]]::new()
foreach ($entry in $affected) {
$row = $entry.Row
if ($null -in @($row.Major, $row.Minor, $row.Build, $row.Type)) { continue }
$key = Get-OsKey $row.Major $row.Minor $row.Build $row.Type
if (-not $Lookup.ContainsKey($key)) { continue }
$desired = [string]$Lookup[$key]
if ($row.Description -ceq $desired) { continue }
$wrong.Add([pscustomobject]@{ Row = $row; Reason = $entry.Reason; Desired = $desired })
}
$updated = 0
$isFullScan = ($InitialReason -eq 'INITIAL')
if ($wrong.Count -gt 0) {
$names = Get-ComputerNames
foreach ($entry in $wrong) {
$row = $entry.Row
$count = Set-DescriptionById -Row $row -DesiredDescription $entry.Desired
$computer = if ($names.ContainsKey($row.Id)) { $names[$row.Id] } else { $row.Id }
$msg = '{0} {1} [{2}] Build={3}; OS={4} -> {5}' -f $entry.Reason,
$computer, $row.Id, $row.Build, $row.Description, $entry.Desired
if ($count -eq 1) {
$updated++
# Full scans log one summary; event-driven corrections log individual changes.
if (-not $isFullScan) { Write-Log "UPDATED $msg" }
} else {
Write-Log "SKIPPED (row changed concurrently): $msg" -Level WARNING
}
}
}
if ($isFullScan) {
Write-Log ('Reconciliation: checked={0}; wrong={1}; updated={2}' -f $affected.Count, $wrong.Count, $updated)
}
}
function Clear-Notifications {
Unregister-Event -SourceIdentifier $eventName -ErrorAction SilentlyContinue
Get-Event -SourceIdentifier $eventName -ErrorAction SilentlyContinue |
Remove-Event -ErrorAction SilentlyContinue
}
function Stop-Listener {
Clear-Notifications
if ($script:listenerStarted) {
try { [void][System.Data.SqlClient.SqlDependency]::Stop($connectionString) }
catch { Write-Log ('SqlDependency.Stop failed: ' + $_.Exception.Message) -Level WARNING }
finally { $script:listenerStarted = $false }
}
}
function Start-Listener {
$script:listenerStarted = [System.Data.SqlClient.SqlDependency]::Start($connectionString)
if (-not $script:listenerStarted) { throw 'SqlDependency.Start returned False.' }
}
try {
# The first Write-Log separates a new run from existing entries when possible.
if ($AsService) { Write-Log 'Service starting...' }
$lookup = New-NameCatalog
Write-Log "Catalog loaded: $($lookup.Count) combinations. Mode=$(if ($AsService) { 'SERVICE' } else { 'ONCE' })."
if (-not $AsService) {
$initial = Get-Snapshot
Process-Changes -Before @{} -After $initial -Lookup $lookup -InitialReason 'INITIAL'
} else {
$hadConnection = $false
$serviceStarted = $false
while ($null -eq $endTime -or (Get-Date) -lt $endTime) {
try {
Start-Listener
# Subscribe before initial reconciliation; own updates generate harmless notifications.
$previous = Get-Snapshot -Subscribe $true
if ($hadConnection) { Write-Log 'SQL connection restored; full reconciliation.' }
$hadConnection = $true
Process-Changes -Before @{} -After $previous -Lookup $lookup -InitialReason 'INITIAL'
if (-not $serviceStarted) {
Write-Log 'Service started.'
$serviceStarted = $true
}
while ($null -eq $endTime -or (Get-Date) -lt $endTime) {
$notification = Wait-Event -SourceIdentifier $eventName -Timeout 10
if ($null -eq $notification) { continue }
$args = $notification.SourceEventArgs
Clear-Notifications
if ($args.Type.ToString() -eq 'Subscribe' -or $args.Info.ToString() -eq 'Invalid') {
throw ('SqlDependency notification rejected: Type={0}, Source={1}, Info={2}' -f $args.Type, $args.Source, $args.Info)
}
# Always re-arm before doing any updates; filter self-notifications via comparison.
$current = Get-Snapshot -Subscribe $true
Process-Changes -Before $previous -After $current -Lookup $lookup
$previous = $current
}
}
catch {
Write-Log ('SQL/listener error: ' + $_.Exception.Message + '; reconnecting in 15 seconds.') -Level ERROR
$hadConnection = $true
Stop-Listener
if ($null -ne $endTime -and (Get-Date) -ge $endTime) { break }
Start-Sleep -Seconds 15
}
finally { Stop-Listener }
}
}
if ($AsService) { Write-Log 'Service stopped.' }
else { Write-Log 'Finished.' }
}
catch {
Write-Log $_.Exception.Message -Level ERROR
throw
}
finally {
Stop-Listener
}