-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-Patch.ps1
More file actions
1341 lines (1110 loc) · 55.1 KB
/
Copy pathInvoke-Patch.ps1
File metadata and controls
1341 lines (1110 loc) · 55.1 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
# DOTS formatting comment
<#
.SYNOPSIS
Deploys a patch across a fleet of Windows endpoints concurrently.
.DESCRIPTION
Primary orchestrator for the toolkit. Resolves a software definition from
Main-Switch.ps1, builds the target list, and fans deployment out across
the fleet via Invoke-RunspacePool. Per machine, runs the pipeline:
ping -> DNS resolution -> version check -> copy patch files
-> execute deploy script -> post-install verify
Timeout is derived dynamically from patch file size (small = 35 min,
large = up to 120 min) and can be overridden. Results come back as a
uniform table regardless of per-machine success, failure, or timeout,
so downstream Format-Table / Export-Csv consumers never have to
special-case missing rows.
Written by Skyler Werner
.EXAMPLE
Invoke-Patch -TargetSoftware Edge
Patches every machine listed in Desktop\Lists\Microsoft_Edge.txt.
.EXAMPLE
Invoke-Patch -TS Chrome -TM WORKSTATION01
Patches a single machine, using the short parameter aliases.
.EXAMPLE
Invoke-Patch -TargetSoftware Edge -ConfirmTimeout -CollectLogs
Deploys with interactive confirmation before killing timed-out tasks
and copies per-machine install logs back to the operator's desktop.
#>
function Invoke-Patch {
[CmdletBinding()]
param(
# Enter the software name. Make sure the software exists in the Main Switch.
[Parameter(Mandatory, Position = 0)]
[Alias("SoftwareName","Target", "SN", "TS")]
[String]
$TargetSoftware,
# Enter a ComputerName to target only one machine.
[Parameter(Position = 1)]
[Alias("ComputerName", "CN", "TM")]
[String]
$TargetMachine,
# Forces patch to run on all machines (Necessary if some file paths are folders with no version info)
[Parameter(Position = 2)]
[Switch]
$Force,
# Skips copying files to machines
[Parameter(Position = 3)]
[Alias("SkipCopy")]
[Switch]
$NoCopy,
# Sets forced timeout for copying in minutes instead of default dynamic timeout based on file size
[Parameter(Position = 4)]
[ValidateRange(0, 120)]
[Int]
$CopyTimeout,
# Sets forced timeout for patching in minutes
[Parameter(Position = 5)]
[ValidateRange(0, 240)]
[Int]
$Timeout,
# Prompts for confirmation before stopping timed-out tasks (default is auto-stop)
[Parameter(Position = 6)]
[Alias("CT")]
[Switch]
$ConfirmTimeout,
# Retrieves detailed per-machine patch logs from remote machines after patching
[Parameter(Position = 7)]
[Alias("GetLogs", "CopyLogs")]
[Switch]
$CollectLogs,
# Overrides the Main-Switch listPath with a custom .txt file of target machines
[Parameter(Position = 8)]
[Alias("ListFile", "TL")]
[String]
$TargetList,
# Emits the results array on the pipeline (in addition to the host table).
# Used by Invoke-PatchGUI to capture results from a background runspace.
[Parameter(Position = 9)]
[Switch]
$PassThru,
# Synchronized hashtable the GUI can poll for per-machine progress
# (Computer -> @{ State, Phase, StartTime, Elapsed }). Passed through
# to Invoke-RunspacePool, which owns the mirroring.
[Parameter(Position = 10)]
[Hashtable]
$ProgressSink
)
begin {
#region --- Extract data from Main Switch ---
# Clears variables to prevent conflicts after Ctrl + C
$varriableArray = @(
"Tag"
"Software"
"ListPath"
"CompliantVer"
"PatchPath"
"PatchName"
"ProcessName"
"PatchScript"
"SoftwarePaths"
"InstallLine"
"KB"
"TargetMachine"
"SoftwareName"
)
Clear-Variable $varriableArray -Scope Global -ErrorAction 0
# Determines switch type
$switch = "Main-Switch.ps1"
# Pulls data from the switch
Set-ExecutionPolicy Bypass -Scope Process -Force *> $null
$switchPath = "$scriptPath\$switch"
$mainSwitch = (Get-Command $switchPath).ScriptBlock
$switchArguments = & $mainSwitch
# Variables from Main Switch are imported
$switchArguments.GetEnumerator() | ForEach-Object {
# Pulls key only if it has a value in hash table
if ($null -ne $($_.Value)) {
# Creates variable from key name
[string]$key = $($_.Key)
$value = $($_.Value)
New-Variable -Name $key -Value $value -Scope Script -Force
}
}
#endregion --- Extract data from Main Switch ---
#region --- Setup before patching ---
# Override the Main-Switch listPath with a custom target list if provided
if ($TargetList) {
if (Test-Path -LiteralPath $TargetList) {
$listPath = $TargetList
}
else {
Write-Warning "TargetList path '$TargetList' does not exist."
break
}
}
# Defines the verbose variable if entered as a parameter
$verbose = $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent
if ($verbose) {
Write-Host ""
Write-Verbose "Verbose has been selected"
Write-Host ""
}
# Ensures the item path for Copy is valid (skip check when patchPath is null, e.g. uninstall-only)
if ($NoCopy.IsPresent -eq $false -and $null -ne $patchPath) {
if (-not (Test-Path "$patchPath\$patchName")) {
Write-Warning "Patch path '$patchPath\$patchName' does not exist. Check $switch for errors."
break
}
}
# Catches mistakes in TargetSoftware param
if ($null -eq $softwarePaths) {
$string = "$switch didn't contain anything matching " + '"' + $targetSoftware + '"' +
". You probably misspelled the software you were trying to patch."
Write-Warning $string
break
}
# Checks that the Patch Script is valid
if (!($patchScript)) {
Write-Warning ('$PathScript' + " string '$patchScript' is not valid. Check $switch for errors.")
break
}
# Checks for PSTools
if ($tag -contains "PSExec") {
if (!(Test-Path "$env:USERPROFILE\Desktop\PSTools\PsExec.exe")) {
Write-Warning ("$env:USERPROFILE\Desktop\PSTools\PsExec.exe was not found! Microsoft " +
".msu updates require this file.")
break
}
}
# Length must be used to determine if Target Machine has data
if ($targetMachine.Length -eq 0) {
# Checks that the list path is valid
if (!(Test-Path $listPath)) {
Write-Warning "'$listPath' is not a valid path."
if (!(Test-Path (Split-Path $listPath))) {
Write-Host "Creating new directory '$(Split-Path $listPath)'... Put your list in here!"
Write-Host "The list needs to be called '$(Split-Path $listPath -Leaf)'"
mkdir (Split-Path $listPath) > $null
}
break
}
# Checks that your list is populated with entries
if ((Get-Content $listPath).Count -lt 1) {
Write-Warning "The list at '$listPath' is empty."
break
}
# Uses Format-ComputerList custom module to clean up list
$list = Get-Content $listPath
$listFormatted = Format-ComputerList $list -ToUpper
}
else {
$listFormatted = Format-ComputerList $targetMachine -ToUpper
}
# Pulls date, admin name, and software (or KB) name
$dateOutput = Get-Date -Format "yyyy-MM-dd-HHmm"
$date = Get-Date -Format "yyyy/MM/dd HH:mm"
$user = $env:USERNAME
# Populates $softwareName
if ($null -eq $softwareName) {
$softwareName = $KB
}
if ($null -eq $softwareName) {
$softwareName = $software
}
# Changes the name of the window
if ($Host.Name -eq "ConsoleHost") {
$Host.Ui.RawUI.WindowTitle = "$software"
}
Write-Host "Beginning patching sequence for " -NoNewline
Write-Host "$software" -ForegroundColor Cyan -NoNewline
Write-Host "..."
#endregion --- Setup before patching ---
} # End begin
process {
#region --- Build config and arguments ---
# Convert PatchScript ScriptBlock to string (scriptblocks cannot cross runspace boundaries)
$patchScriptStr = $patchScript.ToString()
# Build config hashtable with all Main-Switch values for the pipeline
$config = @{
Tag = $tag
Software = $software
SoftwareName = $softwareName
CompliantVer = $compliantVer
PatchPath = $patchPath
PatchName = $patchName
ProcessName = $processName
SoftwarePaths = $softwarePaths
InstallLine = $installLine
KB = $KB
RegistryKey = $registryKey
AdminName = $user
}
# Set version type (defaults to "File" unless explicitly "Product")
if ($versionType -ne "Product") {
$versionType = "File"
}
$config.VersionType = $versionType
# Build argument list for Default.ps1 / Default-PSExec.ps1
if ($tag -match "PsExec") {
$scriptArgList = @(
$patchPath
$patchName
[string]$installLine
)
}
else {
# Pass $config hashtable directly -- Invoke-Command serializes it natively.
# Default.ps1 / Default-NoUninstall.ps1 unpack values from $Args[0].
$scriptArgList = @($config)
}
if ($verbose) {
Write-Host ""
Write-Verbose "Argument List:"
Write-Host ""
$scriptArgList
Write-Host ""
}
# Derive DNS suffix from the active network profile for IP-to-hostname
# resolution. Empty string on a workgroup / unmatched host.
$activeNetwork = if (Get-Command Get-RSLActiveNetwork -ErrorAction SilentlyContinue) {
Get-RSLActiveNetwork
} else { $null }
$dnsSuffix = if ($activeNetwork) { "." + $activeNetwork.DomainFqdn } else { "" }
#endregion --- Build config and arguments ---
#region --- Calculate dynamic timeout ---
# Install timeout from Main-Switch (per-region), defaults to 30 if not set
if (-not $installTimeout) { $installTimeout = 30 }
if ($timeout -ge 1) {
# User provided explicit timeout
$dynamicTimeout = [int]$timeout
}
elseif ($copyTimeout -ge 1) {
# User provided copy timeout; add install time from Main-Switch
$dynamicTimeout = [int]$copyTimeout + $installTimeout
}
else {
# Calculate dynamic timeout based on patch size (preserves Copy-ItemAsJob logic)
$patchSizeBytes = 0
if ($null -ne $patchPath -and (Test-Path $patchPath)) {
(Get-ChildItem $patchPath -Recurse -ErrorAction SilentlyContinue) | ForEach-Object {
$patchSizeBytes += $_.Length
}
}
$divideBy100MB = $patchSizeBytes / 105000000
# Copy time based on file size + install time from Main-Switch
if ($patchSizeBytes -eq 0) { $copyTime = 0 } # No files to copy
elseif ($divideBy100MB -lt 0.1) { $copyTime = 5 } # < 10 MB
elseif (($divideBy100MB -ge 0.1) -and ($divideBy100MB -lt 1)) { $copyTime = 10 } # < 100 MB
elseif (($divideBy100MB -ge 1) -and ($divideBy100MB -lt 2)) { $copyTime = 20 } # < 200 MB
elseif (($divideBy100MB -ge 2) -and ($divideBy100MB -lt 5)) { $copyTime = 30 } # < 500 MB
elseif (($divideBy100MB -ge 5) -and ($divideBy100MB -lt 10)) { $copyTime = 45 } # < 1 GB
elseif (($divideBy100MB -ge 10) -and ($divideBy100MB -lt 30)) { $copyTime = 60 } # < 3 GB
elseif (($divideBy100MB -ge 30) -and ($divideBy100MB -lt 50)) { $copyTime = 75 } # < 5 GB
elseif ($divideBy100MB -ge 50) { $copyTime = 90 } # >= 5 GB
$dynamicTimeout = $copyTime + $installTimeout
}
if ($verbose) {
Write-Verbose "Dynamic Timeout: $dynamicTimeout minutes (install budget: $installTimeout)"
}
#endregion --- Calculate dynamic timeout ---
#region --- Pre-calculate origin file info for copy verification ---
$originFileCount = 0
$originFileSize = 0
$originHashArray = @()
if (-not $NoCopy.IsPresent -and $null -ne $patchPath -and (Test-Path $patchPath)) {
$originFiles = Get-ChildItem $patchPath -Recurse -ErrorAction SilentlyContinue
$originMeasure = $originFiles | Measure-Object -Sum Length
$originFileCount = $originMeasure.Count
$originFileSize = $originMeasure.Sum
# Pre-calculate hashes (top-level files only, matching Copy-ItemAsJob behavior)
$originTopFiles = Get-ChildItem $patchPath -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer }
if ($originTopFiles) {
$originHashArray = @($originTopFiles | Get-FileHash | Select-Object @{N='FileName';E={Split-Path $_.Path -Leaf}}, Hash)
}
}
$config.OriginFileCount = $originFileCount
$config.OriginFileSize = $originFileSize
$config.OriginHashes = $originHashArray
#endregion --- Pre-calculate origin file info for copy verification ---
#region --- Define per-machine pipeline scriptblock ---
$pipelineScriptBlock = {
# All data enters via $args (no $Using: in runspaces)
$computer = $args[0]
$config = $args[1]
$force = $args[2]
$noCopy = $args[3]
$patchScriptStr = $args[4]
$scriptArgList = $args[5]
$dnsSuffix = $args[6]
$date = $args[7]
$adminName = $args[8]
$partialResults = $args[9]
# Inline helper -- strips WinRM boilerplate from exception messages.
# Must be defined inside the scriptblock; runspaces cannot see the
# caller's imported modules (InitialSessionState::CreateDefault).
function _CompressError ([string]$Msg) {
$Msg = $Msg -replace 'Processing data from remote server \S+ failed with the following error message:\s*', ''
$Msg = $Msg -replace 'Connecting to remote server \S+ failed with the following error message\s*:\s*', ''
$Msg = $Msg -replace '\s*For more information, see the about_Remote_Troubleshooting Help topic\.', ''
$Msg = $Msg -replace '^\[.+?\]\s*', ''
$Msg = $Msg -replace '\r?\n', ' '
$Msg = $Msg -replace '\s{2,}', ' '
return $Msg.Trim()
}
$_scriptStart = [DateTime]::Now
# Initialize result object (same schema as original results table)
$result = [PSCustomObject]@{
IPAddress = $null
ComputerName = $null
Status = $null
SoftwareName = $config.SoftwareName
Version = $null
Compliant = $null
NewVersion = $null
ExitCode = $null
Comment = $null
AdminName = $adminName
Date = $date
}
# Determine if input is IP or hostname
if ($computer -match '\.') {
$result.IPAddress = $computer
}
else {
$result.ComputerName = $computer
}
#--- PHASE 1: Reachability (ICMP with WinRM-port fallback for isolation) ---
$PhaseTracker[$computer] = "Pinging"
$pingResult = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
$ipAddr = $null
if ($null -ne $pingResult) {
# ICMP succeeded -- machine is Online
$result.Status = "Online"
if ($null -ne $pingResult.IPV4Address) {
$ipAddr = $pingResult.IPV4Address.IPAddressToString
}
elseif ($null -ne $pingResult.ProtocolAddress) {
$ipAddr = $pingResult.ProtocolAddress
}
}
else {
# ICMP failed -- probe WinRM port 5985 via TCP SYN. Tanium-quarantined
# machines block ICMP (via IPsec policy) but allowlist 5985 for admin
# traffic, so a successful SYN here means the machine is reachable
# and patching can proceed via WinRM. Short 3s timeout keeps the
# cost to truly-offline machines bounded.
$PhaseTracker[$computer] = "Probing WinRM"
$reachable = $false
$tcp = New-Object System.Net.Sockets.TcpClient
try {
$connectTask = $tcp.ConnectAsync($computer, 5985)
$reachable = $connectTask.Wait(3000)
}
catch {
$reachable = $false
}
finally {
$tcp.Close()
}
if ($reachable) {
$result.Status = "Isolated"
}
else {
$result.Status = "Offline"
return $result
}
}
#--- PHASE 2: DNS Resolution ---
$PhaseTracker[$computer] = "DNS Lookup"
if ($computer -match '\.') {
# Input was an IP - resolve to hostname
$result.IPAddress = $computer
try {
$dnsName = [System.Net.Dns]::GetHostByAddress($computer)
if ($null -ne $dnsName) {
$result.ComputerName = $dnsName.HostName.Replace($dnsSuffix, "")
}
}
catch {
$result.Comment = "DNS Request Failed"
}
}
else {
# Input was a hostname - record IP from ping
$result.ComputerName = $computer
if ($null -ne $ipAddr) {
$result.IPAddress = $ipAddr
}
}
# Determine target name for WinRM operations
$targetName = if ($null -ne $result.ComputerName) { $result.ComputerName } else { $result.IPAddress }
if ($null -eq $targetName) {
$result.Comment = "DNS Request Failed"
return $result
}
# Save partial data so it survives if the runspace is stopped later
$partialResults[$computer] = @{
IPAddress = $result.IPAddress
ComputerName = $result.ComputerName
Status = $result.Status
}
#--- PHASE 3: Version Check ---
$PhaseTracker[$computer] = "Version Check"
$tag = $config.Tag
$compliantVer = $config.CompliantVer
if ($tag -contains "RegVersion") {
# Query registry for version info
$registryKeys = $config.RegistryKey
if ($null -eq $registryKeys) {
$registryKeys = @(
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
)
}
try {
$regResult = Invoke-Command -ComputerName $targetName -ScriptBlock {
param($SwName, $RegKeys)
$versions = @()
foreach ($regKey in $RegKeys) {
$children = Get-ChildItem $regKey -ErrorAction SilentlyContinue -Force
if ($null -eq $children) { continue }
$props = Get-ItemProperty $children.PSPath -ErrorAction SilentlyContinue
foreach ($prop in $props) {
if ($prop.DisplayName -match $SwName) {
if ($null -ne $prop.DisplayVersion) {
$versions += $prop.DisplayVersion
}
}
}
}
[PSCustomObject]@{ Version = $versions }
} -ArgumentList $config.Software, $registryKeys -ErrorAction Stop
if ($null -eq $regResult.Version -or $regResult.Version.Count -eq 0) {
$result.Version = "Not Installed"
$result.Compliant = $true
if (-not $force) { return $result }
}
else {
[array]$result.Version = $regResult.Version
}
}
catch {
$result.Comment = "Version Check Failed: $(_CompressError "$_")"
return $result
}
}
else {
# Query file version via Invoke-Command on remote machine
$pathsStr = [string]$config.SoftwarePaths
$versionType = $config.VersionType
try {
$verResult = Invoke-Command -ComputerName $targetName -ScriptBlock {
param($PathsString, $VerType)
$versions = @()
$targetUsers = @()
# Reconstruct path array from space-separated string (split on "C:")
$paths = @()
foreach ($chunk in ($PathsString -split "C:")) {
if ($chunk -eq "") { continue }
$paths += "C:" + $chunk.Trim()
}
foreach ($path in $paths) {
# Handle USER paths (e.g. C:\Users\USER\AppData\...)
if ($path -cmatch 'USER') {
$userArray = (Get-ChildItem "C:\Users" -Force -Directory -ErrorAction SilentlyContinue).Name
$excludeUsers = @('Public', 'ADMINI~1')
$userArray = $userArray | Where-Object {
($_ -notin $excludeUsers) -and ($_ -notmatch 'svc\d*\$')
}
foreach ($usr in $userArray) {
$userPath = $path.Replace('USER', $usr)
if (Test-Path $userPath) {
$item = Get-Item $userPath -Force -ErrorAction SilentlyContinue
if ($null -eq $item) { continue }
if (($item.Mode -match 'a') -or ($item.Mode -eq '------')) {
$fileItem = Get-ChildItem $userPath -Force -ErrorAction SilentlyContinue
if ($VerType -eq 'Product') {
$ver = $fileItem.VersionInfo.ProductVersion
}
else {
$ver = $fileItem.VersionInfo.FileVersionRaw
}
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.ProductVersion }
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.FileVersion }
if ($null -eq $ver) { continue }
if ($ver.GetType().Name -match 'string') {
$ver = [version]($ver.Replace(',','.'))
}
$versions += $ver
$targetUsers += $usr
}
elseif ($item.Mode -match 'd') {
$targetUsers += $usr
}
}
}
}
# Handle standard paths
elseif (Test-Path $path) {
$item = Get-Item $path -Force -ErrorAction SilentlyContinue
if ($null -eq $item) { continue }
if (($item.Mode -match 'a') -or ($item.Mode -eq '------')) {
$fileItem = Get-ChildItem $path -Force -ErrorAction SilentlyContinue
if ($VerType -eq 'Product') {
$ver = $fileItem.VersionInfo.ProductVersion
}
else {
$ver = $fileItem.VersionInfo.FileVersionRaw
}
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.ProductVersion }
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.FileVersion }
if ($null -eq $ver) { continue }
if ($ver.GetType().Name -match 'string') {
$ver = [version]($ver.Replace(',','.'))
}
$versions += $ver
}
elseif ($item.Mode -match 'd') {
# Directory exists (folder-based detection)
}
}
}
[PSCustomObject]@{
Version = $versions
TargetUsers = $targetUsers
}
} -ArgumentList $pathsStr, $versionType -ErrorAction Stop
if ($null -eq $verResult.Version -or $verResult.Version.Count -eq 0) {
$result.Version = "Not Installed"
$result.Compliant = $true
if (-not $force) { return $result }
}
else {
[array]$result.Version = $verResult.Version
}
}
catch {
$result.Comment = "Version Check Failed: $(_CompressError "$_")"
return $result
}
}
# Compliance check
if ($result.Version -ne "Not Installed" -and $null -ne $result.Version) {
$result.Compliant = $true
foreach ($ver in @($result.Version)) {
if ("$ver" -match "Failed|Error") {
$result.Comment = "Version $ver"
continue
}
try {
if ([Version]"$ver" -lt [Version]$compliantVer) {
$result.Compliant = $false
}
}
catch {}
}
if ($result.Compliant -and -not $force) {
return $result
}
}
# Update partial data with version/compliance info
$partialResults[$computer] = @{
IPAddress = $result.IPAddress
ComputerName = $result.ComputerName
Status = $result.Status
Version = $result.Version
Compliant = $result.Compliant
}
#--- PHASE 4: Copy via Robocopy ---
$PhaseTracker[$computer] = "Copying Files"
if ((-not $noCopy) -and ($null -ne $config.PatchPath)) {
$patchPath = $config.PatchPath
$itemFolder = Split-Path $patchPath -Leaf
$remoteDest = "\\$targetName\C`$\Temp"
$destPath = "$remoteDest\$itemFolder"
$copyRequired = $true
# Size verification (fast metadata check via UNC)
if (Test-Path $destPath) {
try {
$destMeasure = Get-ChildItem $destPath -Recurse -ErrorAction SilentlyContinue | Measure-Object -Sum Length
if (($destMeasure.Count -eq $config.OriginFileCount) -and ($destMeasure.Sum -eq $config.OriginFileSize)) {
# Sizes match - verify hashes on remote machine (avoids reading files over network)
if ($config.OriginHashes.Count -gt 0) {
$hashMismatch = $false
try {
$remoteHashes = Invoke-Command -ComputerName $targetName -ScriptBlock {
param($LocalDest, $Folder)
$destItemPath = "$LocalDest\$Folder"
$files = Get-ChildItem $destItemPath -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer }
if ($null -eq $files) { return @() }
$files | Get-FileHash | Select-Object @{N='FileName';E={Split-Path $_.Path -Leaf}}, Hash
} -ArgumentList "C:\Temp", $itemFolder -ErrorAction Stop
foreach ($originHash in $config.OriginHashes) {
$matching = $remoteHashes | Where-Object { $_.FileName -eq $originHash.FileName }
if ($null -eq $matching -or $matching.Hash -ne $originHash.Hash) {
$hashMismatch = $true
break
}
}
}
catch {
$hashMismatch = $true
}
if (-not $hashMismatch) {
$copyRequired = $false
}
}
else {
# No hashes to check, size match is sufficient
$copyRequired = $false
}
}
}
catch {}
}
if ($copyRequired) {
# Remove stale file if a file exists where a directory is expected
if (Test-Path $destPath -PathType Leaf) {
Remove-Item $destPath -Force > $null
}
# robocopy source=contents destination=full path (unlike Copy-Item which nests automatically)
$robocopyArgs = @(
"`"$patchPath`"" # source directory
"`"$destPath`"" # destination directory (includes folder name)
'/E' # copy subdirectories including empty ones
'/R:3' # retry 3 times on failed copies
'/W:5' # wait 5 seconds between retries
'/MT:4' # multi-threaded copy (4 threads)
'/NP' # no progress percentage (cleaner output)
'/NDL' # no directory listing in output
'/NFL' # no file listing in output (keep output concise)
'/NJH' # no job header
'/NJS' # no job summary
)
$robocopyOutput = & robocopy @robocopyArgs 2>&1
$robocopyExit = $LASTEXITCODE
# Robocopy exit codes: 0-7 = success (bitmask), 8+ = failure
if ($robocopyExit -ge 8) {
$exitMeaning = switch ($robocopyExit) {
8 { "Some files could not be copied" }
16 { "Fatal error - no files were copied" }
default { "Unexpected error" }
}
$result.Comment = "Copy Failed (robocopy exit $robocopyExit): $exitMeaning"
return $result
}
}
}
#--- PHASE 5: Install ---
$PhaseTracker[$computer] = "Patching"
$patchScriptBlock = [ScriptBlock]::Create($patchScriptStr)
if ($tag -match "PsExec") {
# PSExec: invoke scriptblock locally on admin workstation
# Default-PSExec.ps1 expects: $patchPath, $patchName, $installLine, [verbose], $computerName (last)
$psexecArgs = @($scriptArgList) + @($targetName)
try {
$installResult = & $patchScriptBlock @psexecArgs
}
catch {
$result.Comment = "Patch Failed: $(_CompressError "$_")"
return $result
}
$result.ExitCode = $installResult.ExitCode
if ($null -ne $installResult.Comment) {
$result.Comment = $installResult.Comment
}
}
else {
# Standard: Invoke-Command to remote machine with Default.ps1 / Default-NoUninstall.ps1
try {
$installResult = Invoke-Command -ComputerName $targetName `
-ScriptBlock $patchScriptBlock `
-ArgumentList $scriptArgList `
-ErrorAction Stop `
-InformationAction Ignore
$result.ExitCode = $installResult.ExitCode
if ($null -ne $installResult.Comment) {
$result.Comment = $installResult.Comment
}
}
catch {
$result.Comment = "Patch Failed: $(_CompressError "$_")"
return $result
}
}
#--- PHASE 6: Post-Install Version Check ---
$PhaseTracker[$computer] = "Verifying"
if ($tag -match "PsExec") {
# PSExec: check version via UNC paths (local read, same as original Invoke-Patch lines 694-710)
$softwarePaths = $config.SoftwarePaths
$versionType = $config.VersionType
$remotePaths = @()
foreach ($sp in @($softwarePaths)) {
$remotePath = "$sp".Replace(":", "`$")
$remotePaths += "\\$targetName\$remotePath"
}
$newVersions = @()
foreach ($rp in $remotePaths) {
$items = Get-ChildItem $rp -Force -ErrorAction SilentlyContinue
foreach ($fileItem in $items) {
if ($versionType -eq "Product") {
$ver = $fileItem.VersionInfo.ProductVersion
}
else {
$ver = $fileItem.VersionInfo.FileVersionRaw
}
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.ProductVersion }
if ($null -eq $ver) { $ver = $fileItem.VersionInfo.FileVersion }
if ($null -ne $ver) { $newVersions += $ver }
}
}
[array]$result.NewVersion = $newVersions
if ([string]$result.NewVersion -eq [string]$result.Version) {
if ([string]$result.NewVersion -ne "") {
$result.NewVersion = "No Change"
}
}
}
elseif ($tag -contains "RegVersion") {
# RegVersion: re-query registry for new version
$registryKeys = $config.RegistryKey
if ($null -eq $registryKeys) {
$registryKeys = @(
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
)
}
try {
$newRegResult = Invoke-Command -ComputerName $targetName -ScriptBlock {
param($SwName, $RegKeys)
$versions = @()
foreach ($regKey in $RegKeys) {
$children = Get-ChildItem $regKey -ErrorAction SilentlyContinue -Force
if ($null -eq $children) { continue }
$props = Get-ItemProperty $children.PSPath -ErrorAction SilentlyContinue
foreach ($prop in $props) {
if ($prop.DisplayName -match $SwName) {
if ($null -ne $prop.DisplayVersion) {
$versions += $prop.DisplayVersion
}
}
}
}
[PSCustomObject]@{ Version = $versions }
} -ArgumentList $config.Software, $registryKeys -ErrorAction Stop
if ($null -eq $newRegResult.Version -or $newRegResult.Version.Count -eq 0) {
[array]$result.NewVersion = "Removed"
}
else {
[array]$result.NewVersion = $newRegResult.Version
}
}
catch {
# Keep existing comment, append version check failure
if ($null -ne $result.Comment) {
$result.Comment = $result.Comment + " | New Version Check Failed: $(_CompressError "$_")"
}
else {
$result.Comment = "New Version Check Failed: $(_CompressError "$_")"
}
}
}
else {
# Standard: NewVersion was returned by Default.ps1 via Invoke-Command
if ($null -ne $installResult.NewVersion) {
[array]$result.NewVersion = $installResult.NewVersion
}
}
# Update Avg Success in the progress display (exit code 0 or 3010 = success)
if ($result.ExitCode -eq 0 -or $result.ExitCode -eq 3010) {
$dur = ([DateTime]::Now - $_scriptStart).TotalSeconds
$StatusMessage['_count'] = [int]$StatusMessage['_count'] + 1
$StatusMessage['_sum'] = [double]$StatusMessage['_sum'] + $dur
$avg = $StatusMessage['_sum'] / $StatusMessage['_count']
$avgSpan = [TimeSpan]::FromSeconds($avg)
if ($avgSpan.TotalMinutes -ge 1) {
$avgStr = "~{0}m {1:D2}s" -f [math]::Floor($avgSpan.TotalMinutes), $avgSpan.Seconds
} else {
$avgStr = "~{0}s" -f [math]::Floor($avgSpan.TotalSeconds)
}
$StatusMessage['Text'] = "Avg Success: $avgStr"
}
return $result
} # End pipeline scriptblock
#endregion --- Define per-machine pipeline scriptblock ---
#region --- Build argument sets and execute ---
# Thread-safe dictionary for partial results from stopped/timed-out runspaces.
# Each runspace writes its progress here after completing ping/DNS and version
# check phases, so the data survives even if the runspace is killed mid-install.
$partialResults = [System.Collections.Concurrent.ConcurrentDictionary[string, hashtable]]::new()
# Build one argument array per machine
$argumentSets = @(
foreach ($machine in $listFormatted) {
, @(
$machine, # $args[0] = Computer
$config, # $args[1] = Config hashtable
$force.IsPresent, # $args[2] = Force
$NoCopy.IsPresent, # $args[3] = NoCopy
$patchScriptStr, # $args[4] = PatchScript as string
$scriptArgList, # $args[5] = ArgumentList for remote script
$dnsSuffix, # $args[6] = DNS Suffix