Repository navigation
Expand file tree
/
Copy pathWUU.ps1
More file actions
1125 lines (1018 loc) · 49.8 KB
/
Copy pathWUU.ps1
File metadata and controls
1125 lines (1018 loc) · 49.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
This script provides a GUI for remotely managing Windows Updates.
.DESCRIPTION
This script provides a GUI for remotely managing Windows Updates. You can check for, download, and install updates remotely. There is also an option to automatically reboot the Computer after installing updates if required.
.EXAMPLE
.\WUU.ps1
This example open the Windows Update Utility.
.NOTES
Author: Tyler Siegrist
Date: 12/14/2016
This script needs to be run as an administrator with the credentials of an administrator on the remote Computers.
There is limited feedback on the download and install processes due to Microsoft restricting the ability to remotely download or install Windows Updates. This is done by using psexec to run a script locally on the remote machine.
#>
#region Synchronized collections
$DisplayHash = [hashtable]::Synchronized(@{})
$runspaceHash = [hashtable]::Synchronized(@{})
$Jobs = [system.collections.arraylist]::Synchronized((New-Object System.Collections.ArrayList))
$JobCleanup = [hashtable]::Synchronized(@{})
$UpdatesHash = [hashtable]::Synchronized(@{})
#endregion Synchronized collections
#region Environment validation
#Validate user is an Administrator
Write-Verbose 'Checking Administrator credentials.'
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "This script must be elevated!`nNow attempting to elevate."
Start-Process -Verb 'Runas' -FilePath 'PowerShell.exe' -ArgumentList "-STA -NoProfile -WindowStyle Hidden -File `"$($MyInvocation.MyCommand.Definition)`""
Break
}
#Ensure that we are running the GUI from the correct location so that scripts & psexec can be accessed.
Set-Location $(Split-Path $MyInvocation.MyCommand.Path)
#Check for PsExec
Write-Verbose 'Checking for psexec.exe.'
if (-Not (Test-Path psexec.exe)) {
Write-Warning ("Psexec.exe missing from {0}!`n Please place file in the path so WUU can work properly" -f (Split-Path $MyInvocation.MyCommand.Path))
Break
}
#Determine if this instance of PowerShell can run WPF (required for GUI)
Write-Verbose 'Checking the apartment state.'
if ($host.Runspace.ApartmentState -ne 'STA') {
Write-Warning "This script must be run in PowerShell started using -STA switch!`nScript will attempt to open PowerShell in STA and run re-run script."
Start-Process -File PowerShell.exe -Argument "-STA -NoProfile -WindowStyle Hidden -File `"$($myinvocation.mycommand.definition)`""
Break
}
#endregion Environment validation
#region Load required assemblies
Write-Verbose 'Loading required assemblies.'
Add-Type -assemblyName PresentationFramework
Add-Type -assemblyName PresentationCore
Add-Type -assemblyName WindowsBase
Add-Type -assemblyName Microsoft.VisualBasic
Add-Type -assemblyName System.Windows.Forms
#endregion Load required assemblies
#region Load XAML
Write-Verbose 'Loading XAML data.'
try {
[xml]$xaml = Get-Content .\WUU.xaml
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$DisplayHash.Window = [Windows.Markup.XamlReader]::Load($reader)
}
catch {
Write-Warning 'Unable to load XAML data!'
Break
}
#endregion
#region ScriptBlocks
#Add new Computer(s) to list
$AddEntry = {
Param ($ComputerName)
Write-Verbose "Adding $ComputerName."
if (Test-Path Exempt.txt) {
Write-Verbose 'Collecting systems from exempt list.'
[string[]]$exempt = Get-Content Exempt.txt
}
#Add to list
foreach ($Computer in $ComputerName) {
$Computer = $Computer.Trim() #Remove any whitspace
if ([System.String]::IsNullOrEmpty($Computer)) {continue} #Do not add if name empty
if ($exempt -contains $Computer) {continue} #Do not add excluded
if (($DisplayHash.Listview.Items | Select-Object -Expand Computer) -contains $Computer) {continue} #Do not add duplicate
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.clientObservable.Add((
New-Object PSObject -Property @{
Computer = $Computer
Available = 0 -as [int]
Downloaded = 0 -as [int]
InstallErrors = 0 -as [int]
Status = "Initalizing."
RebootRequired = $false -as [bool]
Runspace = $null
}))
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
#Setup runspace
($DisplayHash.Listview.Items | Where-Object {$_.Runspace -eq $Null}) | % {
$NewRunspace = [runspacefactory]::CreateRunspace()
$NewRunspace.ApartmentState = "STA"
$NewRunspace.ThreadOptions = "ReuseThread"
$NewRunspace.Open()
$NewRunspace.SessionStateProxy.SetVariable("DisplayHash", $DisplayHash)
$NewRunspace.SessionStateProxy.SetVariable("UpdatesHash", $UpdatesHash)
$NewRunspace.SessionStateProxy.SetVariable("path", $pwd)
$_.Runspace = $NewRunspace
# $PowerShell = [powershell]::Create().AddScript($GetUpdates).AddArgument($_)
# $PowerShell.Runspace = $_.Runspace
# #Save handle so we can later end the runspace
# $Temp = New-Object PSObject -Property @{
# PowerShell = $PowerShell
# Runspace = $PowerShell.BeginInvoke()
# }
# $Jobs.Add($Temp) | Out-Null
}
}
#Clear Computer list
$ClearComputerList = {
#Remove Computers & associated updates
&$removeEntry @($DisplayHash.Listview.Items)
#Update status
$DisplayHash.StatusTextBox.Dispatcher.Invoke('Background', [action] {
$DisplayHash.StatusTextBox.Foreground = 'Black'
$DisplayHash.StatusTextBox.Text = 'Computer List Cleared!'
})
}
#Download available updates
$DownloadUpdates = {
Param ($Computer)
Try {
#Set path for psexec, scripts
Set-Location $Path
#Check download size
$DownloadStats = ($UpdatesHash[$Computer.Computer] | Where-Object {$_.IsDownloaded -eq $false} | Select-Object -ExpandProperty MaxDownloadSize | Measure-Object -Sum)
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Downloading $($DownloadStats.Count) Updates ($([math]::Round($DownloadStats.Sum/1MB))MB)."
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Copy script to remote Computer and execute
if ( ! ( Test-Path -Path "\\$($Computer.Computer)\C$\Admin\Scripts") ) {
New-Item -Path "\\$($Computer.Computer)\C$\Admin\Scripts" -ItemType Directory
}
Copy-Item '.\Scripts\UpdateDownloader.ps1' "\\$($Computer.Computer)\c$\Admin\Scripts" -Force
[int]$DownloadCount = .\PsExec.exe -accepteula -nobanner -s "\\$($Computer.Computer)" cmd.exe /c 'echo . | powershell.exe -ExecutionPolicy Bypass -file C:\Admin\Scripts\UpdateDownloader.ps1'
Remove-Item "\\$($Computer.Computer)\c$\Admin\Scripts\UpdateDownloader.ps1"
if ($LASTEXITCODE -ne 0) {
throw "PsExec failed with error code $LASTEXITCODE"
}
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Download complete.'
$Computer.Downloaded += $DownloadCount
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Check for available updates
$GetUpdates = {
Param ($Computer)
Try {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Checking for updates, this may take some time.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
Set-Location $path
#Check for updates
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID('Microsoft.Update.Session', $Computer.Computer))
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search('IsInstalled=0 and IsHidden=0')
#Save update info in hash to view with 'Show Available Updates'
$UpdatesHash[$Computer.Computer] = $SearchResult.Updates
#Update status
$DownloadCount = @($SearchResult.Updates | Where-Object {$_.IsDownloaded -eq $true}).Count
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Available = $SearchResult.Updates.Count
$Computer.Downloaded = $DownloadCount
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Don't bother checking for reboot if there is nothing to be pending.
# if ($DownloadCount -gt 0) {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Checking for a pending reboot.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Check if there is a pending update
$rebootRequired = (.\PsExec.exe -accepteula -nobanner -s "\\$($Computer.Computer)" cmd.exe /c 'echo . | powershell.exe -ExecutionPolicy Bypass -Command "&{return (New-Object -ComObject "Microsoft.Update.SystemInfo").RebootRequired}"') -eq $true
if ($LASTEXITCODE -ne 0) {
throw "PsExec failed with error code $LASTEXITCODE"
}
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.RebootRequired = [bool]$rebootRequired
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
# }
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Finished checking for updates.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Format errors for Out-GridView
$GetErrors = {
foreach ($err in $error) {
Switch ($err) {
{$err -is [System.Management.Automation.ErrorRecord]} {
$hash = @{
Category = $err.categoryinfo.Category
Activity = $err.categoryinfo.Activity
Reason = $err.categoryinfo.Reason
Type = $err.GetType().ToString()
Exception = ($err.exception -split ': ')[1]
QualifiedError = $err.FullyQualifiedErrorId
CharacterNumber = $err.InvocationInfo.OffsetInLine
LineNumber = $err.InvocationInfo.ScriptLineNumber
Line = $err.InvocationInfo.Line
TargetObject = $err.TargetObject
}
}
Default {
$hash = @{
Category = $err.errorrecord.categoryinfo.category
Activity = $err.errorrecord.categoryinfo.Activity
Reason = $err.errorrecord.categoryinfo.Reason
Type = $err.GetType().ToString()
Exception = ($err.errorrecord.exception -split ': ')[1]
QualifiedError = $err.errorrecord.FullyQualifiedErrorId
CharacterNumber = $err.errorrecord.InvocationInfo.OffsetInLine
LineNumber = $err.errorrecord.InvocationInfo.ScriptLineNumber
Line = $err.errorrecord.InvocationInfo.Line
TargetObject = $err.errorrecord.TargetObject
}
}
}
$object = New-Object PSObject -Property $hash
$object.PSTypeNames.Insert(0, 'ErrorInformation')
$object
}
}
#Install downloaded updates
$InstallUpdates = {
Param ($Computer)
Try {
#Set path for psexec, scripts
Set-Location $path
#Update status
$installCount = ($UpdatesHash[$Computer.Computer] | Where-Object {$_.IsDownloaded -eq $true -and $_.InstallationBehavior.CanRequestUserInput -eq $false} | Measure-Object).Count
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Installing $installCount Updates, this may take some time."
$Computer.InstallErrors = 0
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Copy script to remote Computer and execute
if ( ! ( Test-Path -Path "\\$($Computer.Computer)\C$\Admin\Scripts") ) {
New-Item -Path "\\$($Computer.Computer)\C$\Admin\Scripts" -ItemType Directory
}
Copy-Item .\Scripts\UpdateInstaller.ps1 "\\$($Computer.Computer)\C$\Admin\Scripts" -Force
[int]$installErrors = .\PsExec.exe -accepteula -nobanner -s "\\$($Computer.Computer)" cmd.exe /c 'echo . | powershell.exe -ExecutionPolicy Bypass -file C:\Admin\Scripts\UpdateInstaller.ps1'
Remove-Item "\\$($Computer.Computer)\C$\Admin\Scripts\UpdateInstaller.ps1"
if ($LASTEXITCODE -ne 0) {
throw "PsExec failed with error code $LASTEXITCODE"
}
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Checking if a reboot is required.'
$Computer.InstallErrors = $installErrors
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Check if any updates require reboot
$rebootRequired = (.\PsExec.exe -accepteula -nobanner -s "\\$($Computer.Computer)" cmd.exe /c 'echo . | powershell.exe -ExecutionPolicy Bypass -Command "&{return (New-Object -ComObject "Microsoft.Update.SystemInfo").RebootRequired}"') -eq $true
if ($LASTEXITCODE -ne 0) {
throw "PsExec failed with error code $LASTEXITCODE"
}
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Install complete.'
$Computer.RebootRequired = [bool]$rebootRequired
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Remove Computer(s) from list
$RemoveEntry = {
Param ($Computers)
#Remove Computers from list
foreach ($Computer in $Computers) {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$DisplayHash.clientObservable.Remove($Computer)
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
$CleanUp = {
Param($Computers)
foreach ($Computer in $Computers) {
$UpdatesHash.Remove($Computer.Computer)
$Computer.Runspace.Dispose()
}
}
$NewRunspace = [runspacefactory]::CreateRunspace()
$NewRunspace.ApartmentState = "STA"
$NewRunspace.ThreadOptions = "ReuseThread"
$NewRunspace.Open()
$NewRunspace.SessionStateProxy.SetVariable("DisplayHash", $DisplayHash)
$NewRunspace.SessionStateProxy.SetVariable("UpdatesHash", $UpdatesHash)
$PowerShell = [powershell]::Create().AddScript($CleanUp).AddArgument($Computers)
$PowerShell.Runspace = $NewRunspace
#Save handle so we can later end the runspace
$Temp = New-Object PSObject -Property @{
PowerShell = $PowerShell
Runspace = $PowerShell.BeginInvoke()
}
$Jobs.Add($Temp) | Out-Null
}
#Remove Computer that cannot be pinged
$RemoveOfflineComputer = {
Param ($Computer, $RemoveEntry)
try {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Testing Connectivity.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Verify connectivity
if (Test-Connection -Count 1 -ComputerName $Computer.Computer -Quiet) {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Online.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
else {
#Remove unreachable Computers
$UpdatesHash.Remove($Computer.Computer)
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$DisplayHash.clientObservable.Remove($Computer)
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Report status to WSUS server
$ReportStatus = {
Param ($Computer)
try {
#Set path for psexec, scripts
Set-Location $Path
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Reporting status to WSUS server.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
$ExecStatus = .\PsExec.exe -accepteula -nobanner -s "\\$($Computer.Computer)" cmd.exe /c 'echo . | wuauclt /reportnow'
if ($LASTEXITCODE -ne 0) {
throw "PsExec failed with error code $LASTEXITCODE"
}
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Finished updating status.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Reboot remote Computer
$RestartComputer = {
Param ($Computer, $afterInstall)
try {
#Avoid auto reboot if not enabled and required
if ($afterInstall -and (-not $Computer.RebootRequired -or -not $DisplayHash.AutoRebootCheckBox.IsChecked)) {return}
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Restarting... Waiting for Computer to shutdown.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Restart and wait until remote COM can be connected
if (Get-Command -Name manage-bde.exe) {
manage-bde.exe -protectors c: -disable -rc 1 -cn $Computer.Computer
} else {
Invoke-Command -ComputerName $Computer.Computer -ScriptBlock { Suspend-BitLocker -MountPoint C: -RebootCount 1 }
}
Restart-Computer $Computer.Computer -Force
while (Test-Connection -Count 1 -ComputerName $Computer.Computer -Quiet) { Start-Sleep -Milliseconds 500 } #Wait for Computer to go offline
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Restarting... Waiting for Computer to come online.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
while ($true) {
#Wait for Computer to come online
Start-Sleep -Seconds 5
try {
[activator]::CreateInstance([type]::GetTypeFromProgID('Microsoft.Update.Session', $Computer.Computer))
Break
}
catch {
Start-Sleep -Seconds 5
}
}
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Error occured: $($_.Exception.Message)'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#Start, stop, or restart Windows Update Service
$WUServiceAction = {
Param($Computer, $Action)
try {
#Start Windows Update Service
if ($Action -eq 'Start') {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Starting Windows Update Service'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Start service
Get-Service -ComputerName $($Computer.Computer) -Name 'wuauserv' -ErrorAction Stop | Start-Service -ErrorAction Stop
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Windows Update Service Started'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
#Stop Windows Update Service
elseif ($Action -eq 'Stop') {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Stopping Windows Update Service'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Stop service
Get-Service -ComputerName $Computer.Computer -Name wuauserv -ErrorAction Stop | Stop-Service -ErrorAction Stop
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Windows Update Service Stopped'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
#Restart Windows Update Service
elseif ($Action -eq 'Restart') {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Restarting Windows Update Service'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Restart service
Get-Service -ComputerName $Computer.Computer -Name wuauserv -ErrorAction Stop | Restart-Service -ErrorAction Stop
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = 'Windows Update Service Restarted'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
}
#Invalid action
else {
Write-Error 'Invalid action specified.'
}
}
catch {
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($Computer)
$Computer.Status = "Error occured: $($_.Exception.Message)"
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#Cancel any remaining actions
exit
}
}
#endregion ScriptBlocks
#region Background runspace to clean up Jobs
$JobCleanup.Flag = $true
$NewRunspace = [runspacefactory]::CreateRunspace()
$NewRunspace.ApartmentState = 'STA'
$NewRunspace.ThreadOptions = 'ReuseThread'
$NewRunspace.Open()
$NewRunspace.SessionStateProxy.SetVariable('JobCleanup', $JobCleanup)
$NewRunspace.SessionStateProxy.SetVariable('Jobs', $Jobs)
$JobCleanup.PowerShell = [PowerShell]::Create().AddScript( {
#Routine to handle completed runspaces
do {
foreach ($runspace in $Jobs) {
if ($runspace.Runspace.isCompleted) {
$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.dispose()
$runspace.Runspace = $null
$runspace.powershell = $null
$Jobs.remove($runspace)
}
}
Start-Sleep -Seconds 1
} while ($JobCleanup.Flag)
})
$JobCleanup.PowerShell.Runspace = $NewRunspace
$JobCleanup.Thread = $JobCleanup.PowerShell.BeginInvoke()
#endregion
#region Connect to controls
$DisplayHash.ActionMenu = $DisplayHash.Window.FindName('ActionMenu')
$DisplayHash.AddADContext = $DisplayHash.Window.FindName('AddADContext')
$DisplayHash.AddADMenu = $DisplayHash.Window.FindName('AddADMenu')
$DisplayHash.AddComputerContext = $DisplayHash.Window.FindName('AddComputerContext')
$DisplayHash.AddComputerMenu = $DisplayHash.Window.FindName('AddComputerMenu')
$DisplayHash.AddFileContext = $DisplayHash.Window.FindName('AddFileContext')
$DisplayHash.EnableRebootCheckBox = $DisplayHash.Window.FindName('EnableRebootCheckBox')
$DisplayHash.AutoRebootCheckBox = $DisplayHash.Window.FindName('AutoRebootCheckBox')
$DisplayHash.BrowseFileMenu = $DisplayHash.Window.FindName('BrowseFileMenu')
$DisplayHash.CheckUpdatesContext = $DisplayHash.Window.FindName('CheckUpdatesContext')
$DisplayHash.ClearComputerListMenu = $DisplayHash.Window.FindName('ClearComputerListMenu')
$DisplayHash.DownloadUpdatesContext = $DisplayHash.Window.FindName('DownloadUpdatesContext')
$DisplayHash.ExitMenu = $DisplayHash.Window.FindName('ExitMenu')
$DisplayHash.ExportListMenu = $DisplayHash.Window.FindName('ExportListMenu')
$DisplayHash.GridView = $DisplayHash.Window.FindName('GridView')
$DisplayHash.InstallUpdatesContext = $DisplayHash.Window.FindName('InstallUpdatesContext')
$DisplayHash.Listview = $DisplayHash.Window.FindName('Listview')
$DisplayHash.ListviewContextMenu = $DisplayHash.Window.FindName('ListViewContextMenu')
$DisplayHash.OfflineHostsMenu = $DisplayHash.Window.FindName('OfflineHostsMenu')
$DisplayHash.RemoteDesktopContext = $DisplayHash.Window.FindName('RemoteDesktopContext')
$DisplayHash.RemoveComputerContext = $DisplayHash.Window.FindName('RemoveComputerContext')
$DisplayHash.ReportStatusContext = $DisplayHash.Window.FindName('ReportStatusContext')
$DisplayHash.RestartContext = $DisplayHash.Window.FindName('RestartContext')
$DisplayHash.SelectAllMenu = $DisplayHash.Window.FindName('SelectAllMenu')
$DisplayHash.ShowInstalledContext = $DisplayHash.Window.FindName('ShowInstalledContext')
$DisplayHash.ShowUpdatesContext = $DisplayHash.Window.FindName('ShowUpdatesContext')
$DisplayHash.StatusTextBox = $DisplayHash.Window.FindName('StatusTextBox')
$DisplayHash.UpdateHistoryMenu = $DisplayHash.Window.FindName('UpdateHistoryMenu')
$DisplayHash.ViewErrorMenu = $DisplayHash.Window.FindName('ViewErrorMenu')
$DisplayHash.ViewUpdateLogContext = $DisplayHash.Window.FindName('ViewUpdateLogContext')
$DisplayHash.WindowsUpdateServiceMenu = $DisplayHash.Window.FindName('WindowsUpdateServiceMenu')
$DisplayHash.WURestartServiceMenu = $DisplayHash.Window.FindName('WURestartServiceMenu')
$DisplayHash.WUStartServiceMenu = $DisplayHash.Window.FindName('WUStartServiceMenu')
$DisplayHash.WUStopServiceMenu = $DisplayHash.Window.FindName('WUStopServiceMenu')
#endregion Connect to controls
#region Event ScriptBlocks
$eventWindowInit = { #Runs before opening window
$Script:SortHash = @{}
#Sort event handler
[System.Windows.RoutedEventHandler]$Global:ColumnSortHandler = {
if ($_.OriginalSource -is [System.Windows.Controls.GridViewColumnHeader]) {
Write-Verbose ('{0}' -f $_.Originalsource.getType().FullName)
if ($_.OriginalSource -AND $_.OriginalSource.Role -ne 'Padding') {
$Column = $_.Originalsource.Column.DisplayMemberBinding.Path.Path
Write-Debug ('Sort: {0}' -f $Column)
if ($SortHash[$Column] -eq 'Ascending') {
$SortHash[$Column] = 'Descending'
}
else {
$SortHash[$Column] = 'Ascending'
}
$lastColumnsort = $Column
$DisplayHash.Listview.Items.SortDescriptions.clear()
Write-Verbose ('Sorting {0} by {1}' -f $Column, $SortHash[$Column])
$DisplayHash.Listview.Items.SortDescriptions.Add((New-Object System.ComponentModel.SortDescription $Column, $SortHash[$Column]))
$DisplayHash.Listview.Items.Refresh()
}
}
}
$DisplayHash.Listview.AddHandler([System.Windows.Controls.GridViewColumnHeader]::ClickEvent, $ColumnSortHandler)
#Create and bind the observable collection to the GridView
$DisplayHash.clientObservable = New-Object System.Collections.ObjectModel.ObservableCollection[object]
$DisplayHash.ListView.ItemsSource = $DisplayHash.clientObservable
}
$eventWindowClose = { #Runs when WUU closes
#Halt job processing
$JobCleanup.Flag = $false
#Stop all runspaces
$JobCleanup.PowerShell.Dispose()
#Cleanup
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
}
$eventActionMenu = { #Enable/disable action menu items
$DisplayHash.ClearComputerListMenu.IsEnabled = ($DisplayHash.Listview.Items.Count -gt 0)
$DisplayHash.OfflineHostsMenu.IsEnabled = ($DisplayHash.Listview.Items.Count -gt 0)
$DisplayHash.ViewErrorMenu.IsEnabled = ($Error.Count -gt 0)
}
$eventAddAD = { #Add Computers from Active Directory
#region OUPicker
$OUPickerHash = [hashtable]::Synchronized(@{})
try {
[xml]$xaml = Get-Content .\OUPicker.xaml
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$OUPickerHash.Window = [Windows.Markup.XamlReader]::Load($reader)
}
catch {
Write-Warning 'Unable to load XAML data for OUPicker!'
return
}
$OUPickerHash.OKButton = $OUPickerHash.Window.FindName('OKButton')
$OUPickerHash.CancelButton = $OUPickerHash.Window.FindName('CancelButton')
$OUPickerHash.OUTree = $OUPickerHash.Window.FindName('OUTree')
$OUPickerHash.OKButton.Add_Click( {$OUPickerHash.SelectedOU = $OUPickerHash.OUTree.SelectedItem.Tag; $OUPickerHash.Window.Close()})
$OUPickerHash.CancelButton.Add_Click( {$OUPickerHash.Window.Close()})
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = "(objectCategory=organizationalUnit)"
$Searcher.SearchScope = "OneLevel"
$rootItem = New-Object System.Windows.Controls.TreeViewItem
$rootItem.Header = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
$rootItem.Tag = $Searcher.SearchRoot.distinguishedName
function Populate-Children($node) {
$Searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($node.Tag)")
$Searcher.FindAll() | % {
$childItem = New-Object System.Windows.Controls.TreeViewItem
$childItem.Header = $_.Properties.name[0]
$childItem.Tag = $_.Properties.distinguishedname
Populate-Children($childItem)
$node.AddChild($childItem)
}
}
Populate-Children($rootItem)
$OUPickerHash.OUTree.AddChild($rootItem)
$OUPickerHash.Window.ShowDialog() | Out-Null
#endregion
#Verify user didn't hit 'cancel' before processing
if ($OUPickerHash.SelectedOU) {
#Update status
$DisplayHash.StatusTextBox.Dispatcher.Invoke('Background', [action] {
$DisplayHash.StatusTextBox.Foreground = 'Black'
$DisplayHash.StatusTextBox.Text = 'Querying Active Directory for Computers...'
})
#Search LDAP path
$Searcher = [adsisearcher]''
$Searcher.SearchRoot = [adsi]"LDAP://$($OUPickerHash.SelectedOU)"
$Searcher.Filter = ('(&(objectCategory=Computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))')
$Searcher.PropertiesToLoad.Add('name') | Out-Null
$Results = $Searcher.FindAll()
if ($Results) {
#Add Computers found
&$AddEntry ($Results | % {$_.Properties.name})
#Update status
$DisplayHash.StatusTextBox.Dispatcher.Invoke('Background', [action] {
$DisplayHash.StatusTextBox.Text = "Successfully Imported $($Results.Count) Computers from Active Directory."
})
}
else {
#Update status
$DisplayHash.StatusTextBox.Dispatcher.Invoke('Background', [action] {
$DisplayHash.StatusTextBox.Foreground = 'Red'
$DisplayHash.StatusTextBox.Text = 'No Computers found, verify LDAP path...'
})
}
}
}
$eventAddComputer = { #Add Computers by typing them in manually
#Open prompt
$Computer = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a Computer name or names. Separate Computers with a comma (,) or semi-colon (;).', 'Add Computer(s)')
#Verify Computers were input
if (-Not [System.String]::IsNullOrEmpty($Computer)) {
[string[]]$Computername = $Computer -split ',|;' #Parse
}
if ($Computername) {&$AddEntry $Computername} #Add Computers
}
$eventAddFile = { #Add Computers from a file
#Open file dialog
$dlg = new-object microsoft.win32.OpenFileDialog
$dlg.DefaultExt = '*.txt'
$dlg.Filter = 'Text Files |*.txt;*.csv'
$dlg.Multiselect = $true
$dlg.InitialDirectory = $pwd
[void]$dlg.showdialog()
$Files = $dlg.FileNames
foreach ($File in $Files)
{
#Verify file was selected
if (-Not ([system.string]::IsNullOrEmpty($File))) {
$entries = (Get-Content $File | Where {$_ -ne ''}) #Parse
&$AddEntry $entries #Add Computers
#Update Status
$DisplayHash.StatusTextBox.Dispatcher.Invoke('Background', [action] {
$DisplayHash.StatusTextBox.Foreground = 'Black'
$DisplayHash.StatusTextBox.Text = "Successfully Added $($entries.Count) Computers from $File."
})
}
}
}
$eventGetUpdates = {
$DisplayHash.Listview.SelectedItems | % {
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($GetUpdates).AddArgument($_)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventDownloadUpdates = {
$DisplayHash.Listview.SelectedItems | % {
#Don't bother downloading if nothing available.
if ($_.Available -eq $_.Downloaded) {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($_)
$_.Status = 'There are no updates available to download.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
return
}
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($DownloadUpdates).AddArgument($_)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventInstallUpdates = {
$DisplayHash.Listview.SelectedItems | % {
#Check if there are any updates that are downloaded and don't require user input
if (-not ($UpdatesHash[$_.Computer] | Where-Object {$_.IsDownloaded -and $_.InstallationBehavior.CanRequestUserInput -eq $false})) {
#Update status
$DisplayHash.ListView.Dispatcher.Invoke('Background', [action] {
$DisplayHash.Listview.Items.EditItem($_)
$_.Status = 'There are no updates available that can be installed remotely.'
$DisplayHash.Listview.Items.CommitEdit()
$DisplayHash.Listview.Items.Refresh()
})
#No need to continue if there are no updates to install.
return
}
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($InstallUpdates).AddArgument($_)
# $Temp.PowerShell.AddScript($RestartComputer).AddArgument($_).AddArgument($true)
# $Temp.PowerShell.AddScript($GetUpdates).AddArgument($_)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventRemoveOfflineComputer = {
$DisplayHash.Listview.Items | % {
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($RemoveOfflineComputer).AddArgument($_).AddArgument($RemoveEntry)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventRestartComputer = {
$DisplayHash.Listview.SelectedItems | % {
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($RestartComputer).AddArgument($_).AddArgument($false)
$Temp.PowerShell.AddScript($GetUpdates).AddArgument($_)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventReportStatus = {
$DisplayHash.Listview.SelectedItems | % {
$Temp = "" | Select-Object PowerShell, Runspace
$Temp.PowerShell = [powershell]::Create().AddScript($ReportStatus).AddArgument($_)
$Temp.PowerShell.Runspace = $_.Runspace
$Temp.Runspace = $Temp.PowerShell.BeginInvoke()
$Jobs.Add($Temp) | Out-Null
}
}
$eventKeyDown = {
if ([System.Windows.Input.Keyboard]::IsKeyDown('RightCtrl') -OR [System.Windows.Input.Keyboard]::IsKeyDown('LeftCtrl')) {
Switch ($_.Key) {
'A' {$DisplayHash.Listview.SelectAll()}
'O' {&$eventAddFile}
'S' {&$eventSaveComputerList}
Default {$Null}
}
}
elseif ($_.Key -eq 'Delete') {&$removeEntry @($DisplayHash.Listview.SelectedItems)}
}
$eventRightClick = {
#Set default values
$DisplayHash.RemoveComputerContext.IsEnabled = $false
$DisplayHash.RemoteDesktopContext.IsEnabled = $false
$DisplayHash.CheckUpdatesContext.IsEnabled = $false
$DisplayHash.DownloadUpdatesContext.IsEnabled = $false
$DisplayHash.InstallUpdatesContext.IsEnabled = $false
$DisplayHash.RestartContext.IsEnabled = $false
$DisplayHash.ReportStatusContext.IsEnabled = $false
$DisplayHash.ShowInstalledContext.IsEnabled = $false
$DisplayHash.ShowUpdatesContext.IsEnabled = $false
$DisplayHash.UpdateHistoryMenu.IsEnabled = $false
$DisplayHash.ViewUpdateLogContext.IsEnabled = $false
$DisplayHash.WindowsUpdateServiceMenu.IsEnabled = $false
if ($DisplayHash.Listview.SelectedItems.count -eq 1) {
$DisplayHash.RemoteDesktopContext.IsEnabled = $true
$DisplayHash.ShowInstalledContext.IsEnabled = $true
$DisplayHash.ShowUpdatesContext.IsEnabled = $true
$DisplayHash.UpdateHistoryMenu.IsEnabled = $true
$DisplayHash.ViewUpdateLogContext.IsEnabled = $true
}
if ($DisplayHash.Listview.SelectedItems.count -ge 1) {
$DisplayHash.RemoveComputerContext.IsEnabled = $true
$DisplayHash.CheckUpdatesContext.IsEnabled = $true
$DisplayHash.DownloadUpdatesContext.IsEnabled = $true
$DisplayHash.ReportStatusContext.IsEnabled = $true
$DisplayHash.WindowsUpdateServiceMenu.IsEnabled = $true
}