-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-LocalUpdateStatus.ps1
More file actions
2231 lines (1952 loc) · 109 KB
/
Get-LocalUpdateStatus.ps1
File metadata and controls
2231 lines (1952 loc) · 109 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
<#
PSScriptInfo
.VERSION 1.8.5
.GUID 4b937790-b06b-427f-8c1f-565030ae0227
.AUTHOR Jan Tiedemann
.COMPANYNAME Jan Tiedemann
.COPYRIGHT 2025
.TAGS Updates, WindowsUpdates, Download, Export, Import, WSUS, Offline, BatchInstall
.DESCRIPTION
Enumerates missing or installed Windows Updates on the local computer and returns an array of objects with update details.
Features enhanced batch download-first-then-install workflow with comprehensive progress visualization.
Supports exporting scan results and importing them on other machines for download.
Supports WSUS offline scanning using wsusscn2.cab for air-gapped environments.
Includes interactive installation confirmation and detailed batch processing summaries.
This function operates on the local computer only - run directly on each machine to be scanned.
#>
# Helper function to install updates (.cab via DISM, .msu via WUSA, .exe via silent execution)
function Invoke-UpdateInstallation {
param(
[string]$FilePath,
[string]$KbId,
[string]$Title
)
if (-not (Test-Path $FilePath)) {
Write-Host " Installation failed: File not found - $FilePath" -ForegroundColor Red
return $false
}
$fileExtension = [System.IO.Path]::GetExtension($FilePath).ToLower()
$fileName = Split-Path $FilePath -Leaf
# Special handling for Azure Connected Machine Agent
if ($Title -like "*AzureConnectedMachineAgent*" -or $fileName -like "*azureconnectedmachineagent*") {
Write-Host " Detected Azure Connected Machine Agent update - using specialized installation method..." -ForegroundColor Yellow
# For Azure Connected Machine Agent, try direct service-based installation
try {
Write-Host " Stopping Azure Connected Machine Agent services..." -ForegroundColor Gray
$services = @("himds", "AzureConnectedMachineAgent")
foreach ($svc in $services) {
$service = Get-Service -Name $svc -ErrorAction SilentlyContinue
if ($service -and $service.Status -eq 'Running') {
Stop-Service -Name $svc -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
}
}
}
catch {
Write-Host " Warning: Could not stop Azure services: $($_.Exception.Message)" -ForegroundColor Yellow
}
}
Write-Host " Installing: $fileName" -ForegroundColor Cyan
try {
switch ($fileExtension) {
'.cab' {
# Use DISM for .cab files (primary method)
Write-Host " Using DISM for .cab installation..." -ForegroundColor Gray
$dismArgs = @(
'/Online'
'/Add-Package'
"/PackagePath:$FilePath"
'/Quiet'
'/NoRestart'
)
$process = Start-Process -FilePath 'DISM.exe' -ArgumentList $dismArgs -Wait -PassThru -NoNewWindow
if ($process.ExitCode -eq 0) {
Write-Host " Installation successful: $fileName" -ForegroundColor Green
return $true
}
elseif ($process.ExitCode -eq 3010) {
Write-Host " Installation successful (restart required): $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 2) {
# DISM exit code 2: Invalid command line or access denied
Write-Host " DISM failed (exit code 2: Invalid command or access denied), trying alternative method..." -ForegroundColor Yellow
Write-Host " DEBUG: Title='$Title', FileName='$fileName'" -ForegroundColor Magenta
# Special handling for Azure Connected Machine Agent (improved detection)
$isAzureAgent = ($Title -like "*AzureConnectedMachineAgent*") -or
($Title -like "*Azure Connected Machine Agent*") -or
($fileName -like "*azureconnectedmachineagent*") -or
($fileName -like "*azure*connected*machine*agent*")
Write-Host " DEBUG: Azure agent detection result: $isAzureAgent" -ForegroundColor Magenta
if ($isAzureAgent) {
Write-Host " Azure Connected Machine Agent detected - using specialized extraction..." -ForegroundColor Cyan
# Try using makecab/extract with different parameters for Azure agent
try {
$tempDir = Join-Path $env:TEMP "AzureAgent_$([System.Guid]::NewGuid().ToString('N')[0..7] -join '')"
New-Item -Path $tempDir -ItemType Directory -Force | Out-Null
Write-Host " Extracting Azure Connected Machine Agent package..." -ForegroundColor Gray
# Try different extraction methods for this specific agent
$extractSuccess = $false
# Method 1: extrac32.exe (better for SCOM .cab files)
Write-Host " Trying extrac32.exe for .cab extraction..." -ForegroundColor Gray
$extrac32Process = Start-Process -FilePath 'extrac32.exe' -ArgumentList @("/Y", "/E", "/L", $tempDir, $FilePath) -Wait -PassThru -NoNewWindow
if ($extrac32Process.ExitCode -eq 0) {
$extractSuccess = $true
Write-Host " Extraction successful with extrac32.exe" -ForegroundColor Green
}
# Method 2: Try expand.exe if extrac32.exe failed
if (-not $extractSuccess) {
Write-Host " extrac32.exe failed, trying expand.exe..." -ForegroundColor Yellow
$expandProcess = Start-Process -FilePath 'expand.exe' -ArgumentList @("-F:*", $FilePath, $tempDir, "-R") -Wait -PassThru -NoNewWindow
if ($expandProcess.ExitCode -eq 0) {
$extractSuccess = $true
Write-Host " Extraction successful with expand.exe" -ForegroundColor Green
}
}
if ($extractSuccess) {
# Look for any executable content
Write-Host " Searching for installable content..." -ForegroundColor Gray
$allFiles = Get-ChildItem -Path $tempDir -Recurse -File
Write-Host " Found $($allFiles.Count) files in extracted content:" -ForegroundColor Gray
foreach ($file in $allFiles) {
Write-Host " - $($file.Name) ($($file.Extension))" -ForegroundColor DarkGray
}
# Try to find and install any executable content
$installSuccess = $false
# Look for .exe files first
$exeFiles = $allFiles | Where-Object { $_.Extension -eq '.exe' }
foreach ($exeFile in $exeFiles) {
Write-Host " Attempting to install: $($exeFile.Name)" -ForegroundColor Yellow
try {
$exeProcess = Start-Process -FilePath $exeFile.FullName -ArgumentList @('/quiet', '/norestart') -Wait -PassThru -NoNewWindow
if ($exeProcess.ExitCode -eq 0 -or $exeProcess.ExitCode -eq 3010) {
$installSuccess = $true
Write-Host " Installation successful via extracted .exe: $($exeFile.Name)" -ForegroundColor Green
break
}
}
catch {
Write-Host " Failed to execute $($exeFile.Name): $($_.Exception.Message)" -ForegroundColor Red
}
}
# If no .exe worked, try .msi files
if (-not $installSuccess) {
$msiFiles = $allFiles | Where-Object { $_.Extension -eq '.msi' }
foreach ($msiFile in $msiFiles) {
Write-Host " Attempting to install MSI: $($msiFile.Name)" -ForegroundColor Yellow
try {
$msiProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', $msiFile.FullName, '/quiet', '/norestart', 'REBOOT=ReallySuppress') -Wait -PassThru -NoNewWindow
if ($msiProcess.ExitCode -eq 0 -or $msiProcess.ExitCode -eq 3010 -or $msiProcess.ExitCode -eq 1638) {
$installSuccess = $true
Write-Host " Installation successful via extracted .msi: $($msiFile.Name)" -ForegroundColor Green
break
}
}
catch {
Write-Host " Failed to execute $($msiFile.Name): $($_.Exception.Message)" -ForegroundColor Red
}
}
}
# If no .msi worked, try .msp files (Microsoft Patch files)
if (-not $installSuccess) {
$mspFiles = $allFiles | Where-Object { $_.Extension -eq '.msp' }
foreach ($mspFile in $mspFiles) {
Write-Host " Attempting to install MSP patch: $($mspFile.Name)" -ForegroundColor Yellow
try {
$mspProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/p', $mspFile.FullName, '/quiet', '/norestart', 'REBOOT=ReallySuppress') -Wait -PassThru -NoNewWindow
if ($mspProcess.ExitCode -eq 0 -or $mspProcess.ExitCode -eq 3010 -or $mspProcess.ExitCode -eq 1638) {
$installSuccess = $true
Write-Host " Installation successful via extracted .msp: $($mspFile.Name)" -ForegroundColor Green
break
}
}
catch {
Write-Host " Failed to execute $($mspFile.Name): $($_.Exception.Message)" -ForegroundColor Red
}
}
}
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
if ($installSuccess) {
return $true
}
else {
Write-Host " Azure Connected Machine Agent installation failed via all extraction methods" -ForegroundColor Red
return $false
}
}
else {
Write-Host " Failed to extract Azure Connected Machine Agent package" -ForegroundColor Red
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
return $false
}
}
catch {
Write-Host " Azure Connected Machine Agent specialized installation failed: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# Standard fallback method for other .cab files
try {
$tempDir = Join-Path $env:TEMP "CabExtract_$([System.Guid]::NewGuid().ToString('N')[0..7] -join '')"
New-Item -Path $tempDir -ItemType Directory -Force | Out-Null
Write-Host " Attempting .cab extraction and manual installation..." -ForegroundColor Gray
# Try extrac32.exe first (better for SCOM .cab files)
Write-Host " Trying extrac32.exe for .cab extraction..." -ForegroundColor Gray
$extrac32Process = Start-Process -FilePath 'extrac32.exe' -ArgumentList @("/Y", "/E", "/L", $tempDir, $FilePath) -Wait -PassThru -NoNewWindow
if ($extrac32Process.ExitCode -eq 0) {
Write-Host " Extraction successful with extrac32.exe" -ForegroundColor Green
}
else {
# If extrac32.exe fails, try expand.exe as fallback
Write-Host " extrac32.exe failed (exit code: $($extrac32Process.ExitCode)), trying expand.exe..." -ForegroundColor Yellow
$expandProcess = Start-Process -FilePath 'expand.exe' -ArgumentList @("-F:*", $FilePath, $tempDir) -Wait -PassThru -NoNewWindow
if ($expandProcess.ExitCode -eq 0) {
Write-Host " Extraction successful with expand.exe" -ForegroundColor Green
}
else {
Write-Host " Both extraction methods failed. extrac32.exe: $($extrac32Process.ExitCode), expand.exe: $($expandProcess.ExitCode)" -ForegroundColor Red
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
return $false
}
}
# Analysis phase - check what was extracted
$installationSuccess = $false
# Debug: List all extracted files
Write-Host " Analyzing extracted content..." -ForegroundColor Gray
$allExtractedFiles = Get-ChildItem -Path $tempDir -Recurse -File
Write-Host " Found $($allExtractedFiles.Count) files in extracted content:" -ForegroundColor Gray
foreach ($file in $allExtractedFiles) {
Write-Host " - $($file.Name) ($($file.Extension.ToLower())) [$(($file.Length/1KB).ToString('F1')) KB]" -ForegroundColor DarkGray
}
# Check if this is a SCOM-related update and prioritize .msp files
$isSCOMUpdate = ($Title -like "*SCOM*") -or
($Title -like "*System Center*") -or
($Title -like "*Operations Manager*") -or
($fileName -like "*scom*") -or
($fileName -like "*mom*")
# For SCOM updates, check .msp files first
if ($isSCOMUpdate) {
Write-Host " SCOM-related update detected - checking for .msp files first..." -ForegroundColor Cyan
$mspFiles = Get-ChildItem -Path $tempDir -Filter "*.msp" -Recurse
if ($mspFiles) {
Write-Host " Found $($mspFiles.Count) .msp file(s), attempting SCOM installation..." -ForegroundColor Cyan
foreach ($mspFile in $mspFiles) {
Write-Host " Installing SCOM .msp patch: $($mspFile.Name)" -ForegroundColor Gray
# Enhanced .msp installation arguments for SCOM Agent
$mspArgs = @(
'/p'
$mspFile.FullName
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
'ALLUSERS=1'
'/l*v'
(Join-Path $env:TEMP "SCOM_MSP_Extract_$([System.Guid]::NewGuid().ToString('N')[0..7] -join '').log")
)
$mspProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList $mspArgs -Wait -PassThru -NoNewWindow
if ($mspProcess.ExitCode -eq 0) {
$installationSuccess = $true
Write-Host " SCOM installation successful via extracted .msp: $($mspFile.Name)" -ForegroundColor Green
break
}
elseif ($mspProcess.ExitCode -eq 3010) {
$installationSuccess = $true
Write-Host " SCOM installation successful (restart required): $($mspFile.Name)" -ForegroundColor Yellow
break
}
elseif ($mspProcess.ExitCode -eq 1638) {
$installationSuccess = $true
Write-Host " SCOM patch already applied: $($mspFile.Name)" -ForegroundColor Yellow
break
}
elseif ($mspProcess.ExitCode -eq 1605) {
Write-Host " SCOM .msp installation failed: No products found to patch - $($mspFile.Name)" -ForegroundColor Red
Write-Host " This indicates the SCOM Agent is not installed or the patch is not applicable" -ForegroundColor Yellow
}
elseif ($mspProcess.ExitCode -eq 1619) {
Write-Host " SCOM .msp installation failed: Package couldn't be opened - $($mspFile.Name)" -ForegroundColor Red
Write-Host " Verify the .msp file integrity and permissions" -ForegroundColor Yellow
}
else {
Write-Host " SCOM .msp installation failed (Exit code: $($mspProcess.ExitCode)): $($mspFile.Name)" -ForegroundColor Red
$logFile = $mspArgs | Where-Object { $_ -like "*.log" }
if ($logFile -and (Test-Path $logFile)) {
Write-Host " Check SCOM installation log for details: $logFile" -ForegroundColor Cyan
}
}
}
if (-not $installationSuccess) {
Write-Host " SCOM Agent patch installation failed. Common issues:" -ForegroundColor Yellow
Write-Host " - Ensure SCOM Agent is installed before applying patches" -ForegroundColor Gray
Write-Host " - Check if the patch matches the installed SCOM Agent version" -ForegroundColor Gray
Write-Host " - Verify Administrator privileges" -ForegroundColor Gray
Write-Host " - Check Windows Event Log for additional error details" -ForegroundColor Gray
}
}
else {
Write-Host " No .msp files found in .cab file." -ForegroundColor Yellow
}
}
# Look for .msu files in extracted content (if not SCOM or SCOM .msp failed)
if (-not $installationSuccess) {
$msuFiles = Get-ChildItem -Path $tempDir -Filter "*.msu" -Recurse
if ($msuFiles) {
Write-Host " Found $($msuFiles.Count) .msu file(s), attempting installation..." -ForegroundColor Cyan
foreach ($msuFile in $msuFiles) {
Write-Host " Installing .msu file: $($msuFile.Name)" -ForegroundColor Gray
$wusaProcess = Start-Process -FilePath 'wusa.exe' -ArgumentList @($msuFile.FullName, '/quiet', '/norestart') -Wait -PassThru -NoNewWindow
if ($wusaProcess.ExitCode -eq 0 -or $wusaProcess.ExitCode -eq 3010) {
$installationSuccess = $true
Write-Host " Installation successful via extracted .msu: $fileName" -ForegroundColor Green
break
}
}
}
}
# Look for .msi files in extracted content if .msu installation failed
if (-not $installationSuccess) {
$msiFiles = Get-ChildItem -Path $tempDir -Filter "*.msi" -Recurse
if ($msiFiles) {
Write-Host " Found $($msiFiles.Count) .msi file(s), attempting installation..." -ForegroundColor Cyan
foreach ($msiFile in $msiFiles) {
Write-Host " Installing .msi file: $($msiFile.Name)" -ForegroundColor Gray
$msiArgs = @(
'/i'
$msiFile.FullName
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
)
$msiProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList $msiArgs -Wait -PassThru -NoNewWindow
if ($msiProcess.ExitCode -eq 0) {
$installationSuccess = $true
Write-Host " Installation successful via extracted .msi: $fileName" -ForegroundColor Green
break
}
elseif ($msiProcess.ExitCode -eq 3010) {
$installationSuccess = $true
Write-Host " Installation successful via extracted .msi (restart required): $fileName" -ForegroundColor Yellow
break
}
elseif ($msiProcess.ExitCode -eq 1638) {
$installationSuccess = $true
Write-Host " Installation skipped: Product already installed - $fileName" -ForegroundColor Yellow
break
}
else {
Write-Host " .msi installation failed (Exit code: $($msiProcess.ExitCode)): $($msiFile.Name)" -ForegroundColor Red
}
}
}
# Look for .msp files (Microsoft Patch files) if .msi installation failed
if (-not $installationSuccess) {
$mspFiles = Get-ChildItem -Path $tempDir -Filter "*.msp" -Recurse
if ($mspFiles) {
Write-Host " Found $($mspFiles.Count) .msp file(s), attempting installation..." -ForegroundColor Cyan
# Check if this is a SCOM Agent related patch
$isSCOMPatch = ($Title -like "*SCOM*") -or
($Title -like "*System Center Operations Manager*") -or
($Title -like "*Operations Manager*") -or
($fileName -like "*scom*") -or
($fileName -like "*mom*") -or
($mspFiles | Where-Object { $_.Name -like "*scom*" -or $_.Name -like "*mom*" -or $_.Name -like "*opsmgr*" })
if ($isSCOMPatch) {
Write-Host " SCOM Agent patch detected - using enhanced installation method..." -ForegroundColor Yellow
}
foreach ($mspFile in $mspFiles) {
Write-Host " Installing .msp patch: $($mspFile.Name)" -ForegroundColor Gray
# Enhanced .msp installation arguments for SCOM Agent
$mspArgs = if ($isSCOMPatch) {
@(
'/p'
$mspFile.FullName
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
'ALLUSERS=1'
'/l*v'
(Join-Path $env:TEMP "SCOM_MSP_Install_$([System.Guid]::NewGuid().ToString('N')[0..7] -join '').log")
)
}
else {
@(
'/p'
$mspFile.FullName
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
)
}
$mspProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList $mspArgs -Wait -PassThru -NoNewWindow
# Enhanced exit code handling for .msp files
if ($mspProcess.ExitCode -eq 0) {
$installationSuccess = $true
Write-Host " Installation successful via extracted .msp: $($mspFile.Name)" -ForegroundColor Green
break
}
elseif ($mspProcess.ExitCode -eq 3010) {
$installationSuccess = $true
Write-Host " Installation successful via extracted .msp (restart required): $($mspFile.Name)" -ForegroundColor Yellow
break
}
elseif ($mspProcess.ExitCode -eq 1638) {
$installationSuccess = $true
Write-Host " Installation skipped: Patch already applied - $($mspFile.Name)" -ForegroundColor Yellow
break
}
elseif ($mspProcess.ExitCode -eq 1605) {
Write-Host " .msp installation failed: No products found to patch - $($mspFile.Name)" -ForegroundColor Red
Write-Host " This may indicate the base product (SCOM Agent) is not installed or the patch is not applicable" -ForegroundColor Yellow
}
elseif ($mspProcess.ExitCode -eq 1619) {
Write-Host " .msp installation failed: Package couldn't be opened - $($mspFile.Name)" -ForegroundColor Red
Write-Host " Verify the .msp file integrity and permissions" -ForegroundColor Yellow
}
elseif ($mspProcess.ExitCode -eq 1636) {
Write-Host " .msp installation failed: Patch package couldn't be opened - $($mspFile.Name)" -ForegroundColor Red
}
elseif ($mspProcess.ExitCode -eq 1633) {
Write-Host " .msp installation failed: Platform not supported - $($mspFile.Name)" -ForegroundColor Red
}
else {
Write-Host " .msp installation failed (Exit code: $($mspProcess.ExitCode)): $($mspFile.Name)" -ForegroundColor Red
if ($isSCOMPatch) {
$logFile = $mspArgs | Where-Object { $_ -like "*.log" }
if ($logFile -and (Test-Path $logFile)) {
Write-Host " Check SCOM installation log for details: $logFile" -ForegroundColor Cyan
}
}
}
}
# If SCOM patch failed, provide additional guidance
if (-not $installationSuccess -and $isSCOMPatch) {
Write-Host " SCOM Agent patch installation failed. Common issues:" -ForegroundColor Yellow
Write-Host " - Ensure SCOM Agent is installed before applying patches" -ForegroundColor Gray
Write-Host " - Check if the patch matches the installed SCOM Agent version" -ForegroundColor Gray
Write-Host " - Verify Administrator privileges" -ForegroundColor Gray
Write-Host " - Check Windows Event Log for additional error details" -ForegroundColor Gray
}
}
}
}
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
if ($installationSuccess) {
return $true
}
else {
# Check if this looks like a SCOM-related update for enhanced error messaging
$isSCOMRelated = ($Title -like "*SCOM*") -or
($Title -like "*System Center*") -or
($Title -like "*Operations Manager*") -or
($fileName -like "*scom*")
Write-Host " No installable content found in extracted .cab file: $fileName" -ForegroundColor Red
if ($isSCOMRelated) {
Write-Host " SCOM Agent update detected. Common issues:" -ForegroundColor Yellow
Write-Host " - Ensure SCOM Agent is installed before applying updates" -ForegroundColor Gray
Write-Host " - Check if this update is applicable to your SCOM Agent version" -ForegroundColor Gray
Write-Host " - Some SCOM updates require specific prerequisites" -ForegroundColor Gray
Write-Host " - Verify the .cab file contains the expected .msp files" -ForegroundColor Gray
}
else {
Write-Host " The .cab file may require manual installation or specific prerequisites" -ForegroundColor Yellow
}
return $false
}
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
Write-Host " Alternative installation methods failed: $fileName" -ForegroundColor Red
return $false
}
catch {
Write-Host " Alternative installation failed with error: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
if ($process.ExitCode -eq 50) {
Write-Host " Installation skipped: Package not applicable to this system - $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 87) {
Write-Host " Installation failed: Invalid parameter - $fileName (Exit code: 87)" -ForegroundColor Red
return $false
}
elseif ($process.ExitCode -eq 1460) {
Write-Host " Installation failed: Package already installed - $fileName" -ForegroundColor Yellow
return $true
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
return $false
}
}
'.msu' {
# Use WUSA for .msu files
Write-Host " Using WUSA for .msu installation..." -ForegroundColor Gray
$wusaArgs = @(
"$FilePath"
'/quiet'
'/norestart'
)
$process = Start-Process -FilePath 'wusa.exe' -ArgumentList $wusaArgs -Wait -PassThru -NoNewWindow
if ($process.ExitCode -eq 0) {
Write-Host " Installation successful: $fileName" -ForegroundColor Green
return $true
}
elseif ($process.ExitCode -eq 3010) {
Write-Host " Installation successful (restart required): $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq -2145124329) {
Write-Host " Installation skipped: Update already installed - $fileName" -ForegroundColor Yellow
return $true
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
return $false
}
}
'.exe' {
# Use direct execution for .exe files with silent installation switches
Write-Host " Using silent execution for .exe installation..." -ForegroundColor Gray
# Common silent switches for Microsoft executable updates
$exeArgs = @()
# Try to determine appropriate silent switches based on filename/title
if ($fileName -match "malicious|removal|tool|msrt" -or $Title -match "Malicious Software Removal Tool") {
# Windows Malicious Software Removal Tool uses /Q
$exeArgs = @('/Q')
Write-Host " Detected Malicious Software Removal Tool - using /Q switch" -ForegroundColor Gray
}
elseif ($fileName -match "defender|antimalware" -or $Title -match "Defender|Antimalware") {
# Windows Defender updates often use /q
$exeArgs = @('/q')
Write-Host " Detected Defender/Antimalware update - using /q switch" -ForegroundColor Gray
}
else {
# Generic Microsoft executable updates - try common silent switches
$exeArgs = @('/quiet')
Write-Host " Using generic silent switch: /quiet" -ForegroundColor Gray
}
$process = Start-Process -FilePath $FilePath -ArgumentList $exeArgs -Wait -PassThru -NoNewWindow
if ($process.ExitCode -eq 0) {
Write-Host " Installation successful: $fileName" -ForegroundColor Green
return $true
}
elseif ($process.ExitCode -eq 3010) {
Write-Host " Installation successful (restart required): $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 1) {
Write-Host " Installation completed with warnings: $fileName" -ForegroundColor Yellow
return $true
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
Write-Host " Note: Some .exe files may require specific switches or manual installation" -ForegroundColor Gray
return $false
}
}
'.msi' {
# Use msiexec for .msi files
Write-Host " Using msiexec for .msi installation..." -ForegroundColor Gray
$msiArgs = @(
'/i'
$FilePath
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
)
$process = Start-Process -FilePath 'msiexec.exe' -ArgumentList $msiArgs -Wait -PassThru -NoNewWindow
if ($process.ExitCode -eq 0) {
Write-Host " Installation successful: $fileName" -ForegroundColor Green
return $true
}
elseif ($process.ExitCode -eq 3010) {
Write-Host " Installation successful (restart required): $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 1638) {
Write-Host " Installation skipped: Product already installed - $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 1605) {
Write-Host " Installation failed: This action is only valid for products that are currently installed - $fileName" -ForegroundColor Red
return $false
}
elseif ($process.ExitCode -eq 1619) {
Write-Host " Installation failed: Package could not be opened - $fileName" -ForegroundColor Red
return $false
}
elseif ($process.ExitCode -eq 1633) {
Write-Host " Installation failed: Platform not supported - $fileName" -ForegroundColor Red
return $false
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
Write-Host " Note: MSI error codes can indicate specific installation issues" -ForegroundColor Gray
return $false
}
}
'.msp' {
# Use msiexec for .msp files (Microsoft Patch files)
Write-Host " Using msiexec for .msp patch installation..." -ForegroundColor Gray
# Check if this is a SCOM Agent related patch
$isSCOMPatch = ($Title -like "*SCOM*") -or
($Title -like "*System Center Operations Manager*") -or
($Title -like "*Operations Manager*") -or
($fileName -like "*scom*") -or
($fileName -like "*mom*") -or
($fileName -like "*opsmgr*")
if ($isSCOMPatch) {
Write-Host " SCOM Agent patch detected - using enhanced installation method..." -ForegroundColor Yellow
}
# Enhanced .msp installation arguments for SCOM Agent
$mspArgs = if ($isSCOMPatch) {
@(
'/p'
$FilePath
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
'ALLUSERS=1'
'/l*v'
(Join-Path $env:TEMP "SCOM_MSP_Direct_$([System.Guid]::NewGuid().ToString('N')[0..7] -join '').log")
)
}
else {
@(
'/p'
$FilePath
'/quiet'
'/norestart'
'REBOOT=ReallySuppress'
)
}
$process = Start-Process -FilePath 'msiexec.exe' -ArgumentList $mspArgs -Wait -PassThru -NoNewWindow
# Enhanced exit code handling for .msp files
if ($process.ExitCode -eq 0) {
Write-Host " Installation successful: $fileName" -ForegroundColor Green
return $true
}
elseif ($process.ExitCode -eq 3010) {
Write-Host " Installation successful (restart required): $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 1638) {
Write-Host " Installation skipped: Patch already applied - $fileName" -ForegroundColor Yellow
return $true
}
elseif ($process.ExitCode -eq 1605) {
Write-Host " Installation failed: No products found to patch - $fileName" -ForegroundColor Red
if ($isSCOMPatch) {
Write-Host " This may indicate the SCOM Agent is not installed or the patch is not applicable" -ForegroundColor Yellow
}
return $false
}
elseif ($process.ExitCode -eq 1619) {
Write-Host " Installation failed: Package couldn't be opened - $fileName" -ForegroundColor Red
Write-Host " Verify the .msp file integrity and permissions" -ForegroundColor Yellow
return $false
}
elseif ($process.ExitCode -eq 1636) {
Write-Host " Installation failed: Patch package couldn't be opened - $fileName" -ForegroundColor Red
return $false
}
elseif ($process.ExitCode -eq 1633) {
Write-Host " Installation failed: Platform not supported - $fileName" -ForegroundColor Red
return $false
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
if ($isSCOMPatch) {
$logFile = $mspArgs | Where-Object { $_ -like "*.log" }
if ($logFile -and (Test-Path $logFile)) {
Write-Host " Check SCOM installation log for details: $logFile" -ForegroundColor Cyan
}
Write-Host " SCOM Agent patch installation failed. Common issues:" -ForegroundColor Yellow
Write-Host " - Ensure SCOM Agent is installed before applying patches" -ForegroundColor Gray
Write-Host " - Check if the patch matches the installed SCOM Agent version" -ForegroundColor Gray
Write-Host " - Verify Administrator privileges" -ForegroundColor Gray
Write-Host " - Check Windows Event Log for additional error details" -ForegroundColor Gray
}
return $false
}
else {
Write-Host " Installation failed: $fileName (Exit code: $($process.ExitCode))" -ForegroundColor Red
if ($isSCOMPatch) {
$logFile = $mspArgs | Where-Object { $_ -like "*.log" }
if ($logFile -and (Test-Path $logFile)) {
Write-Host " Check SCOM installation log for details: $logFile" -ForegroundColor Cyan
}
Write-Host " SCOM Agent patch installation failed. Common issues:" -ForegroundColor Yellow
Write-Host " - Ensure SCOM Agent is installed before applying patches" -ForegroundColor Gray
Write-Host " - Check if the patch matches the installed SCOM Agent version" -ForegroundColor Gray
Write-Host " - Verify Administrator privileges" -ForegroundColor Gray
Write-Host " - Check Windows Event Log for additional error details" -ForegroundColor Gray
}
return $false
}
}
default {
Write-Host " Installation failed: Unsupported file type '$fileExtension' for $fileName" -ForegroundColor Red
Write-Host " Supported types: .cab (DISM), .msu (WUSA), .msi (msiexec), .msp (msiexec), .exe (Silent)" -ForegroundColor Gray
return $false
}
}
}
catch {
Write-Host " Installation failed: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# Helper function to download updates with enhanced progress
function Invoke-UpdateDownload {
param(
[string]$Url,
[string]$DestinationPath,
[string]$KbId,
[string]$Title,
[int]$CurrentIndex = 1,
[int]$TotalCount = 1
)
if ([string]::IsNullOrWhiteSpace($Url)) {
return @{
Success = $false
FilePath = $null
FileSize = 0
Reason = "No download URL available"
}
}
try {
# Extract filename from URL or create one based on KB ID
$fileName = Split-Path $Url -Leaf
if ([string]::IsNullOrWhiteSpace($fileName) -or $fileName -notmatch '\.\w+$') {
$fileName = "KB$KbId.msu"
}
$fullPath = Join-Path $DestinationPath $fileName
# Progress header
Write-Host "`n[$CurrentIndex/$TotalCount] Downloading KB$KbId" -ForegroundColor Cyan
Write-Host " Title: $Title" -ForegroundColor Gray
Write-Host " File: $fileName" -ForegroundColor Gray
# Check if file already exists
if (Test-Path $fullPath) {
$existingSize = (Get-Item $fullPath).Length
$existingSizeMB = [math]::Round($existingSize / 1MB, 2)
Write-Host " Status: File already exists ($existingSizeMB MB)" -ForegroundColor Yellow
return @{
Success = $true
FilePath = $fullPath
FileSize = $existingSize
Reason = "File already existed"
}
}
Write-Host " URL: $Url" -ForegroundColor Gray
Write-Host " Downloading..." -ForegroundColor Yellow
# Create a stopwatch for download timing
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Use System.Net.WebClient for better progress control
$webClient = New-Object System.Net.WebClient
$webClient.Headers.Add("User-Agent", "PowerShell Windows Update Downloader")
# Add progress event handler
$progressAction = {
param($senderObj, $progressArgs)
$percentComplete = [math]::Round(($progressArgs.BytesReceived / $progressArgs.TotalBytesToReceive) * 100, 1)
$receivedMB = [math]::Round($progressArgs.BytesReceived / 1MB, 2)
$totalMB = [math]::Round($progressArgs.TotalBytesToReceive / 1MB, 2)
if ($progressArgs.TotalBytesToReceive -gt 0) {
Write-Progress -Activity "Downloading $fileName" -Status "$receivedMB MB / $totalMB MB ($percentComplete%)" -PercentComplete $percentComplete
}
}
# Register the event
Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -Action $progressAction | Out-Null
try {
# Start the download
$webClient.DownloadFile($Url, $fullPath)
}
finally {
# Clean up events and webclient
Get-EventSubscriber | Where-Object { $_.SourceObject -eq $webClient } | Unregister-Event
$webClient.Dispose()
Write-Progress -Activity "Downloading $fileName" -Completed
}
$stopwatch.Stop()
if (Test-Path $fullPath) {
$fileSize = (Get-Item $fullPath).Length
$fileSizeMB = [math]::Round($fileSize / 1MB, 2)
$downloadSpeed = if ($stopwatch.Elapsed.TotalSeconds -gt 0) {
[math]::Round($fileSize / $stopwatch.Elapsed.TotalSeconds / 1MB, 2)
}
else { 0 }
Write-Host " Status: Download completed successfully" -ForegroundColor Green
Write-Host " Size: $fileSizeMB MB" -ForegroundColor Green
Write-Host " Time: $($stopwatch.Elapsed.ToString('mm\:ss')) (${downloadSpeed} MB/s)" -ForegroundColor Green
return @{
Success = $true
FilePath = $fullPath
FileSize = $fileSize
Reason = "Downloaded successfully"
}
}
else {
Write-Host " Status: Download failed - File not found after download" -ForegroundColor Red
return @{
Success = $false
FilePath = $null
FileSize = 0
Reason = "File not found after download"
}
}
}
catch {
Write-Host " Status: Download failed - $($_.Exception.Message)" -ForegroundColor Red
return @{
Success = $false
FilePath = $null
FileSize = 0
Reason = $_.Exception.Message
}
}
}
# Helper function to install a batch of downloaded updates with progress visualization
function Invoke-UpdateBatchInstallation {
param(
[array]$UpdatesToInstall,
[string]$InstallationMode = "Sequential" # Sequential or Parallel (future enhancement)
)
if (-not $UpdatesToInstall -or $UpdatesToInstall.Count -eq 0) {
Write-Host "No updates to install." -ForegroundColor Yellow
return
}
$totalUpdates = $UpdatesToInstall.Count
$successfulInstalls = 0
$failedInstalls = 0
$installResults = @()
Write-Host ("`n" + "=" * 60) -ForegroundColor Magenta
Write-Host "STARTING BATCH INSTALLATION" -ForegroundColor Magenta
Write-Host ("=" * 60) -ForegroundColor Magenta
Write-Host "Mode: $InstallationMode" -ForegroundColor White
Write-Host "Total updates to install: $totalUpdates" -ForegroundColor White
Write-Host ("=" * 60) -ForegroundColor Magenta
for ($i = 0; $i -lt $totalUpdates; $i++) {
$update = $UpdatesToInstall[$i]
$currentIndex = $i + 1
Write-Host "`n[$currentIndex/$totalUpdates] Installing KB$($update.KbId)" -ForegroundColor Magenta
Write-Host " Title: $($update.Title)" -ForegroundColor Gray
Write-Host " File: $(Split-Path $update.DownloadedFilePath -Leaf)" -ForegroundColor Gray
# Create installation progress bar
$percentComplete = [math]::Round(($currentIndex / $totalUpdates) * 100, 1)
Write-Progress -Activity "Installing Windows Updates" -Status "Installing update $currentIndex of $totalUpdates (KB$($update.KbId))" -PercentComplete $percentComplete
$installStart = Get-Date
$installResult = Invoke-UpdateInstallation -FilePath $update.DownloadedFilePath -KbId $update.KbId -Title $update.Title
$installEnd = Get-Date
$installDuration = $installEnd - $installStart
$resultObj = [PSCustomObject]@{
KbId = $update.KbId
Title = $update.Title
FilePath = $update.DownloadedFilePath
Success = $installResult
Duration = $installDuration
InstallationTime = $installEnd
}
if ($installResult) {
$successfulInstalls++
Write-Host " Status: Installation completed successfully" -ForegroundColor Green
Write-Host " Duration: $($installDuration.ToString('mm\:ss'))" -ForegroundColor Green
}
else {
$failedInstalls++
Write-Host " Status: Installation failed" -ForegroundColor Red
Write-Host " Duration: $($installDuration.ToString('mm\:ss'))" -ForegroundColor Red
}
$installResults += $resultObj
# Show progress summary
Write-Host " Progress: $successfulInstalls successful, $failedInstalls failed, $($totalUpdates - $currentIndex) remaining" -ForegroundColor Cyan
}
# Complete the progress bar
Write-Progress -Activity "Installing Windows Updates" -Completed
# Final installation summary
Write-Host ("`n" + "=" * 60) -ForegroundColor Magenta
Write-Host "BATCH INSTALLATION COMPLETED" -ForegroundColor Magenta
Write-Host ("=" * 60) -ForegroundColor Magenta
Write-Host "Total updates processed: $totalUpdates" -ForegroundColor White
Write-Host "Successful installations: $successfulInstalls" -ForegroundColor Green
Write-Host "Failed installations: $failedInstalls" -ForegroundColor Red
Write-Host "Success rate: $([math]::Round(($successfulInstalls / $totalUpdates) * 100, 1))%" -ForegroundColor $(if ($successfulInstalls -eq $totalUpdates) { 'Green' } elseif ($successfulInstalls -gt $failedInstalls) { 'Yellow' } else { 'Red' })
if ($failedInstalls -gt 0) {
Write-Host "`nFailed installations:" -ForegroundColor Red
$installResults | Where-Object { -not $_.Success } | ForEach-Object {
Write-Host " - KB$($_.KbId): $($_.Title)" -ForegroundColor Red
}
}
if ($successfulInstalls -gt 0) {
Write-Host "`nRecommendation: Restart the computer to complete the installation of $successfulInstalls update(s)" -ForegroundColor Yellow
}
Write-Host ("`n" + "=" * 60) -ForegroundColor Magenta
return $installResults
}