-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUpdate-Modules.ps1
More file actions
2356 lines (2356 loc) · 108 KB
/
Copy pathUpdate-Modules.ps1
File metadata and controls
2356 lines (2356 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 7.0
#Requires -modules Microsoft.PowerShell.ThreadJob
#Requires -RunAsAdministrator
<#
Author: Harze2k
Date: 2026-06-28
Version: 4.2
- Added -ReplaceLockedModuleOnReboot and -AllowVersionedSubfolder to Update-Modules.
- Fixed parallel retrieval of online module metadata and per-module repository filtering.
- Fixed cleanup for modules outside PSResourceGet-managed locations, including $PSHOME.
- Reduced normal-path console output and consolidated operation summaries.
- Fixed primary-manifest filtering, parallel result counts, and cleanup status reporting.
#>
#region Check-PSResourceRepository
function Check-PSResourceRepository {
<#
.SYNOPSIS
Ensures PSResourceGet and the required repositories are available.
.DESCRIPTION
Loads Microsoft.PowerShell.PSResourceGet and configures PSGallery, NuGetGallery,
and NuGet as trusted repositories with the priorities used by this script.
.PARAMETER ImportDependencies
Reimports Microsoft.PowerShell.PSResourceGet even when its commands are available.
.PARAMETER ForceInstall
Reinstalls Microsoft.PowerShell.PSResourceGet when running Windows PowerShell 5.1.
.PARAMETER TimeoutSeconds
Maximum time allowed for dependency and repository setup operations.
.INPUTS
None.
.OUTPUTS
System.Boolean. Returns false when setup cannot continue; successful setup writes no value.
.EXAMPLE
Check-PSResourceRepository -ImportDependencies
Loads PSResourceGet and verifies the repository configuration.
.NOTES
Requires administrator rights and network access to the configured repositories.
.LINK
Register-PSResourceRepository
#>
[CmdletBinding()]
param (
[switch]$ImportDependencies,
[switch]$ForceInstall,
[int]$TimeoutSeconds = 30
)
$isPSCore = $PSVersionTable.PSVersion.Major -ge 6
$hasPSResourceGet = [bool](Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue)
New-Log "PowerShell version: $($PSVersionTable.PSVersion) | PSCore: $isPSCore | PSResourceGet available: $hasPSResourceGet"
function Invoke-WithTimeout {
[CmdletBinding()]
param (
[Parameter(Mandatory)][scriptblock]$ScriptBlock,
[int]$Timeout = 30,
[string]$OperationName = 'Operation'
)
$runspace = $null
$powershell = $null
try {
$runspace = [runspacefactory]::CreateRunspace()
$runspace.Open()
$powershell = [powershell]::Create()
$powershell.Runspace = $runspace
[void]$powershell.AddScript($ScriptBlock)
$handle = $powershell.BeginInvoke()
$completed = $handle.AsyncWaitHandle.WaitOne($Timeout * 1000)
if (-not $completed) {
New-Log "$OperationName timed out after $Timeout seconds." -Level WARNING
$powershell.Stop()
return $null
}
if ($powershell.HadErrors) {
$errorMsg = $powershell.Streams.Error | ForEach-Object { $_.ToString() } | Join-String -Separator '; '
New-Log "$OperationName had errors: $errorMsg" -Level WARNING
}
return $powershell.EndInvoke($handle)
}
catch {
New-Log "$OperationName failed" -Level ERROR
return $null
}
finally {
if ($powershell) { $powershell.Dispose() }
if ($runspace) { $runspace.Close(); $runspace.Dispose() }
}
}
function Set-TlsProtocol {
try {
$existingProtocols = [Net.ServicePointManager]::SecurityProtocol
$tls12Enum = [Net.SecurityProtocolType]::Tls12
if (-not ($existingProtocols -band $tls12Enum)) {
[Net.ServicePointManager]::SecurityProtocol = $existingProtocols -bor $tls12Enum
New-Log "TLS 1.2 security protocol enabled."
}
else {
New-Log "TLS 1.2 already enabled."
}
return $true
}
catch {
New-Log "Unable to set TLS 1.2" -Level ERROR
return $false
}
}
function Install-PSResourceGetForPS5 {
[CmdletBinding()]
param (
[int]$Timeout = 30,
[switch]$Force
)
New-Log "Attempting to install Microsoft.PowerShell.PSResourceGet for PS 5.1$(if ($Force) { ' (Force)' })..."
try {
$psGalleryScript = { Get-PSRepository -Name 'PSGallery' -ErrorAction SilentlyContinue }
$psGallery = Invoke-WithTimeout -ScriptBlock $psGalleryScript -Timeout $Timeout -OperationName "Get-PSRepository PSGallery"
if ($null -eq $psGallery) {
New-Log "Could not query PSGallery repository - may need manual registration." -Level WARNING
}
elseif (-not $psGallery.Trusted) {
New-Log "Setting PSGallery to Trusted..."
$setRepoScript = { Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted -ErrorAction Stop }
Invoke-WithTimeout -ScriptBlock $setRepoScript -Timeout $Timeout -OperationName "Set-PSRepository Trusted" | Out-Null
New-Log "PSGallery set to Trusted." -Level SUCCESS
}
else {
New-Log "PSGallery is already trusted."
}
}
catch {
New-Log "Error configuring PSGallery" -Level ERROR
}
$forceFlag = $Force.IsPresent
$installScript = [scriptblock]::Create(@"
`$ErrorActionPreference = 'Stop'
Install-Module -Name 'Microsoft.PowerShell.PSResourceGet' -Repository 'PSGallery' -Scope AllUsers -Force:$forceFlag -AllowClobber -AcceptLicense -SkipPublisherCheck -Confirm:`$false
"@)
New-Log "Installing Microsoft.PowerShell.PSResourceGet via Install-Module..."
Invoke-WithTimeout -ScriptBlock $installScript -Timeout ($Timeout * 2) -OperationName "Install-Module PSResourceGet" | Out-Null
try {
Import-Module -Name 'Microsoft.PowerShell.PSResourceGet' -Force -ErrorAction Stop -Verbose:$false
New-Log "Successfully imported Microsoft.PowerShell.PSResourceGet." -Level SUCCESS
return $true
}
catch {
New-Log "Failed to import Microsoft.PowerShell.PSResourceGet" -Level ERROR
return $false
}
}
function Import-PSResourceGetModule {
[CmdletBinding()]
param ([switch]$Force)
$action = if ($Force) { "Force importing" } else { "Importing" }
New-Log "$action Microsoft.PowerShell.PSResourceGet module..."
try {
Import-Module -Name 'Microsoft.PowerShell.PSResourceGet' -Force:$Force -ErrorAction Stop -Verbose:$false
New-Log "Successfully imported PSResourceGet." -Level SUCCESS
return $true
}
catch {
New-Log "Failed to import PSResourceGet" -Level ERROR
return $false
}
}
function Register-RepositoryPSResourceGet {
[CmdletBinding()]
param (
[Parameter(Mandatory)][string]$Name,
[string]$Uri,
[Parameter(Mandatory)][int]$Priority,
[string]$ApiVersion = 'v3',
[switch]$IsPSGallery
)
try {
$repository = Get-PSResourceRepository -Name $Name -ErrorAction SilentlyContinue
$needsUpdate = ($null -eq $repository) -or ($repository.Priority -ne $Priority) -or (-not $repository.Trusted)
if (-not $IsPSGallery -and $Uri -and $repository) {
$currentUri = if ($repository.Uri) { $repository.Uri.AbsoluteUri } else { $null }
$needsUpdate = $needsUpdate -or ($currentUri -ne $Uri)
}
if ($needsUpdate) {
if ($IsPSGallery) {
New-Log "Configuring PSGallery (Priority: $Priority, Trusted: True)."
Set-PSResourceRepository -Name $Name -Priority $Priority -Trusted -ErrorAction Stop
}
else {
New-Log "Registering repository '$Name' (Uri: $Uri, Priority: $Priority)."
$registerParams = @{
Name = $Name
Uri = $Uri
Priority = $Priority
Trusted = $true
Force = $true
PassThru = $false
ErrorAction = 'Stop'
}
if ($ApiVersion -eq 'v2') {
$registerParams.ApiVersion = 'v2'
New-Log "Using API Version V2 for '$Name'."
}
Register-PSResourceRepository @registerParams
}
New-Log "Successfully configured '$Name' repository." -Level SUCCESS
}
else {
New-Log "'$Name' repository already configured correctly."
}
return $true
}
catch {
New-Log "Failed to configure '$Name'" -Level ERROR
return $false
}
}
Set-TlsProtocol | Out-Null
$needsDependencyWork = (-not $hasPSResourceGet) -or $ImportDependencies.IsPresent
if ($needsDependencyWork) {
if ($ImportDependencies.IsPresent -and $hasPSResourceGet) {
New-Log "-ImportDependencies specified. Re-importing PSResourceGet module..."
}
if ($isPSCore) {
if (-not (Import-PSResourceGetModule -Force:$ImportDependencies.IsPresent)) {
New-Log "Could not import PSResourceGet in PS7." -Level ERROR
return $false
}
}
else {
$existingModule = Get-Module -Name 'Microsoft.PowerShell.PSResourceGet' -ListAvailable -ErrorAction SilentlyContinue
if ($ForceInstall.IsPresent -or -not $existingModule) {
if ($ForceInstall.IsPresent -and $existingModule) {
New-Log "-ForceInstall specified. Reinstalling PSResourceGet..."
}
if (-not (Install-PSResourceGetForPS5 -Timeout $TimeoutSeconds -Force:$ForceInstall.IsPresent)) {
New-Log "Could not install PSResourceGet. Cannot continue." -Level ERROR
return $false
}
}
else {
if (-not (Import-PSResourceGetModule -Force:$ImportDependencies.IsPresent)) {
New-Log "Could not import existing PSResourceGet module." -Level ERROR
return $false
}
}
}
$hasPSResourceGet = [bool](Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue)
}
if (-not $hasPSResourceGet) {
New-Log "PSResourceGet cmdlets still not available. Aborting." -Level ERROR
return $false
}
New-Log "PSResourceGet cmdlets are available. Configuring repositories..."
$repositories = @(
@{ Name = 'PSGallery'; Uri = $null; Priority = 30; IsPSGallery = $true }
@{ Name = 'NuGetGallery'; Uri = 'https://api.nuget.org/v3/index.json'; Priority = 40 }
@{ Name = 'NuGet'; Uri = 'https://www.nuget.org/api/v2'; Priority = 50; ApiVersion = 'v2' }
)
$overallSuccess = $true
foreach ($repo in $repositories) {
$splatParams = @{
Name = $repo.Name
Priority = $repo.Priority
IsPSGallery = [bool]$repo.IsPSGallery
}
if ($repo.Uri) { $splatParams.Uri = $repo.Uri }
if ($repo.ApiVersion) { $splatParams.ApiVersion = $repo.ApiVersion }
if (-not (Register-RepositoryPSResourceGet @splatParams)) {
$overallSuccess = $false
}
}
if ($overallSuccess) {
New-Log "All repositories configured successfully." -Level SUCCESS
}
else {
New-Log "Some repositories could not be configured." -Level WARNING
}
}
#endregion Check-PSResourceRepository
#region Get-ModuleInfo
function Get-ModuleInfo {
<#
.SYNOPSIS
Builds an inventory of installed PowerShell modules.
.DESCRIPTION
Scans the supplied directories for module manifests and PSGetModuleInfo.xml files,
parses their metadata in parallel, normalizes installation paths, and groups the
results by module name.
.PARAMETER Paths
Directories to scan recursively. Paths from PSModulePath are typically supplied.
.PARAMETER IgnoredModules
Module names to exclude from the returned inventory.
.PARAMETER ThrottleLimit
Maximum number of files processed concurrently.
.INPUTS
None.
.OUTPUTS
System.Collections.Specialized.OrderedDictionary. Keys are module names and values
are arrays of installation records containing version, path, prerelease, and author data.
.EXAMPLE
$paths = $env:PSModulePath -split [IO.Path]::PathSeparator
$inventory = Get-ModuleInfo -Paths $paths -IgnoredModules 'BurntToast'
Scans standard module paths and excludes BurntToast.
.NOTES
Requires PowerShell 7 or later for ForEach-Object -Parallel.
.LINK
Get-ModuleUpdateStatus
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string[]]$Paths,
[string[]]$IgnoredModules = @(),
[int]$ThrottleLimit = ([System.Environment]::ProcessorCount * 2)
)
$helperFunctionDefinitions = @{
"New-Log" = ${function:New-Log}.ToString()
"Parse-ModuleVersion" = ${function:Parse-ModuleVersion}.ToString()
"Get-ManifestVersionInfo" = ${function:Get-ManifestVersionInfo}.ToString()
"Resolve-ModuleVersion" = ${function:Resolve-ModuleVersion}.ToString()
"Get-ModuleformPath" = ${function:Get-ModuleformPath}.ToString()
"Get-ModuleInfoFromXml" = ${function:Get-ModuleInfoFromXml}.ToString()
"Test-IsResourceFile" = ${function:Test-IsResourceFile}.ToString()
}
foreach ($funcName in $helperFunctionDefinitions.Keys) {
if ([string]::IsNullOrWhiteSpace($helperFunctionDefinitions[$funcName])) {
Write-Error "Helper function '$funcName' could not be found. It must be loaded."
return
}
}
$scanPaths = @($Paths | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Sort-Object -Unique)
New-Log "Scanning $($scanPaths.Count) module path(s) for manifests and PSGetModuleInfo.xml files..."
$fileDiscoveryStartTime = Get-Date
$allPotentialFiles = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($dir in $scanPaths) {
try {
if (-not (Test-Path -LiteralPath $dir -PathType Container)) {
New-Log "Skipping missing module path '$dir'." -Level WARNING
continue
}
$psd1Files = @(Get-ChildItem -LiteralPath $dir -Recurse -File -Filter "*.psd1" -ErrorAction Stop)
$xmlFiles = @(Get-ChildItem -LiteralPath $dir -Recurse -File -Filter "PSGetModuleInfo.xml" -ErrorAction Stop)
foreach ($file in $psd1Files) { $allPotentialFiles.Add($file) }
foreach ($file in $xmlFiles) { $allPotentialFiles.Add($file) }
}
catch {
New-Log "Could not scan module path '$dir'" -Level ERROR
}
}
$allPotentialFiles = @($allPotentialFiles | Sort-Object FullName -Unique)
$fileDiscoveryDuration = (Get-Date) - $fileDiscoveryStartTime
if ($allPotentialFiles.Count -eq 0) {
New-Log "No potential module files found to process." -Level WARNING
return [ordered]@{}
}
New-Log "Found $($allPotentialFiles.Count) candidate file(s) in $([math]::Round($fileDiscoveryDuration.TotalSeconds, 2)) seconds; parsing with throttle $ThrottleLimit." -Level VERBOSE
$allFoundModulesFromParallel = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
$skippedFiles = [System.Collections.Concurrent.ConcurrentBag[string]]::new()
$fallbackFiles = [System.Collections.Concurrent.ConcurrentBag[string]]::new()
$failedFiles = [System.Collections.Concurrent.ConcurrentBag[string]]::new()
$null = $allPotentialFiles | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel {
$fileInfo = $_
$filePath = $fileInfo.FullName
$fileExtension = $fileInfo.Extension
$VerbosePreference = $using:VerbosePreference
$allFoundModulesFromParallel = $using:allFoundModulesFromParallel
$skippedFiles = $using:skippedFiles
$fallbackFiles = $using:fallbackFiles
$failedFiles = $using:failedFiles
$localHelperFunctionDefinitions = $using:helperFunctionDefinitions
foreach ($funcName in $localHelperFunctionDefinitions.Keys) {
$funcDefinition = $localHelperFunctionDefinitions[$funcName]
if (-not [string]::IsNullOrWhiteSpace($funcDefinition)) {
Set-Item -Path "function:global:$funcName" -Value ([scriptblock]::Create($funcDefinition))
}
}
if (Test-IsResourceFile -Path $filePath) {
$skippedFiles.Add($filePath)
return
}
if ($fileExtension -eq '.psd1') {
$manifestInfoObj = $null
$testManifestOutput = $null
$usedFallback = $false
try {
$testManifestOutput = Test-ModuleManifest -Path $filePath -ErrorAction Stop -WarningAction SilentlyContinue -Verbose:$false
}
catch {
$testManifestOutput = $null
$usedFallback = $true
}
if ($testManifestOutput) {
try {
$manifestInfoObj = Get-ManifestVersionInfo -ResData $testManifestOutput -Quick -ErrorAction Stop -WarningAction SilentlyContinue
}
catch {
$manifestInfoObj = $null
$usedFallback = $true
}
}
if (-not $manifestInfoObj) {
$usedFallback = $true
try {
$manifestInfoObj = Get-ManifestVersionInfo -ModuleFilePath $filePath -ErrorAction Stop -WarningAction SilentlyContinue
}
catch {
$manifestInfoObj = $null
}
}
if ($usedFallback -and $manifestInfoObj) {
$fallbackFiles.Add($filePath)
}
$manifestInfosToProcess = @()
if ($manifestInfoObj) {
if ($manifestInfoObj -is [array] -or $manifestInfoObj -is [System.Collections.IList]) {
$manifestInfosToProcess = $manifestInfoObj
}
else {
$manifestInfosToProcess = @($manifestInfoObj)
}
}
foreach ($mInfo in $manifestInfosToProcess) {
if ($mInfo -and $mInfo.ModuleVersion -and $mInfo.ModuleName) {
$allFoundModulesFromParallel.Add([PSCustomObject]@{
ModuleName = $mInfo.ModuleName
ModuleVersion = $mInfo.ModuleVersion
ModuleVersionString = $mInfo.ModuleVersionString
BasePath = $mInfo.BasePath
isPreRelease = $mInfo.isPreRelease
PreReleaseLabel = $mInfo.PreReleaseLabel
Author = $mInfo.Author
})
}
}
if ($manifestInfosToProcess.Count -eq 0) {
$failedFiles.Add($filePath)
}
}
elseif ($fileExtension -eq '.xml') {
$xmlInfo = Get-ModuleInfoFromXml -XmlFilePath $filePath -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if ($xmlInfo -and $xmlInfo.ModuleName -and $xmlInfo.ModuleVersion) {
$allFoundModulesFromParallel.Add([PSCustomObject]@{
ModuleName = $xmlInfo.ModuleName
ModuleVersion = $xmlInfo.ModuleVersion
ModuleVersionString = $xmlInfo.ModuleVersionString
BasePath = $xmlInfo.BasePath
isPreRelease = $xmlInfo.isPreRelease
PreReleaseLabel = $xmlInfo.PreReleaseLabel
Author = $xmlInfo.Author
})
}
else {
$failedFiles.Add($filePath)
}
}
}
$allFoundModulesArray = $allFoundModulesFromParallel.ToArray()
if ($allFoundModulesArray.Count -eq 0) {
New-Log "No valid module data collected after parallel processing." -Level WARNING
return [ordered]@{}
}
$uniqueModules = $allFoundModulesArray | Group-Object -Property ModuleName, BasePath, ModuleVersionString | ForEach-Object { $_.Group[0] }
$resultModules = [ordered]@{}
$modulesGroupedByName = $uniqueModules | Where-Object { $null -ne $_.ModuleName -and $_.ModuleName -notmatch '^\d+(\.\d+)+$' } | Group-Object ModuleName
foreach ($nameGroup in $modulesGroupedByName) {
$moduleName = $nameGroup.Name
$groupWithNormalizedPaths = $nameGroup.Group | Where-Object { $null -ne $_ } | ForEach-Object {
$newObject = $_ | Select-Object *
if ($null -ne $newObject.BasePath -and -not ([string]::IsNullOrWhiteSpace($moduleName))) {
$currentBasePath = $newObject.BasePath
$normalizedCurrentPath = $currentBasePath.TrimEnd('\', '/') -replace '/', '\'
$expectedEnding = "\$moduleName"
if (-not $normalizedCurrentPath.EndsWith($expectedEnding, [System.StringComparison]::OrdinalIgnoreCase)) {
$leafName = Split-Path $normalizedCurrentPath -Leaf
$parentOfCurrent = Split-Path $normalizedCurrentPath -Parent -ErrorAction SilentlyContinue
$parentLeafName = if ($parentOfCurrent) { Split-Path $parentOfCurrent -Leaf -ErrorAction SilentlyContinue } else { $null }
if ($parentLeafName -eq $moduleName -and $leafName -match '^\d+(\.\d+){1,3}(-.+)?$') {
$newObject.BasePath = $parentOfCurrent
}
elseif ($leafName -eq 'Modules' -or $leafName -eq 'Documents') {
$newObject.BasePath = Join-Path -Path $normalizedCurrentPath -ChildPath $moduleName -ErrorAction SilentlyContinue
}
else {
$newObject.BasePath = $normalizedCurrentPath
}
}
else {
$newObject.BasePath = $normalizedCurrentPath
}
}
$newObject
}
$modulesGroupedByBasePath = $groupWithNormalizedPaths | Where-Object { $null -ne $_.BasePath } | Group-Object -Property BasePath
$finalModuleLocations = [System.Collections.Generic.List[object]]::new()
foreach ($basePathGroup in $modulesGroupedByBasePath) {
$currentBasePath = $basePathGroup.Name
$versionsInPathGroup = $basePathGroup.Group | Group-Object -Property @{ Expression = { if ($_.ModuleVersion -is [version]) { $_.ModuleVersion } else { $_.ModuleVersionString } } }
foreach ($versionGroup in $versionsInPathGroup) {
$representativeEntry = $versionGroup.Group | Sort-Object -Property @{Expression = { $_.ModuleVersion -is [version] }; Descending = $true }, ModuleVersionString | Select-Object -First 1
if ($representativeEntry) {
$outputObject = [PSCustomObject]@{
ModuleName = $moduleName
ModuleVersion = $representativeEntry.ModuleVersion
ModuleVersionString = $representativeEntry.ModuleVersionString
BasePath = $currentBasePath
IsPreRelease = $representativeEntry.IsPreRelease
PreReleaseLabel = $representativeEntry.PreReleaseLabel
Author = $representativeEntry.Author
}
$finalModuleLocations.Add($outputObject)
}
}
}
if ($finalModuleLocations.Count -gt 0) {
$sortedLocations = $finalModuleLocations | Sort-Object BasePath, @{Expression = { $_.ModuleVersion }; Ascending = $true }
$resultModules[$moduleName] = $sortedLocations
}
}
$finalSortedModules = [ordered]@{}
foreach ($key in ($resultModules.Keys | Sort-Object)) {
if ($IgnoredModules -notcontains $key) {
$finalSortedModules[$key] = $resultModules[$key]
}
else {
New-Log "Skipping module '$key' as it is in the IgnoredModules list (final filter)." -Level VERBOSE
}
}
$totalFunctionDuration = (Get-Date) - $fileDiscoveryStartTime
$installationCount = @($finalSortedModules.Values | ForEach-Object { $_ }).Count
$inventoryLevel = if ($failedFiles.Count -gt 0) { 'WARNING' } else { 'SUCCESS' }
New-Log "Inventory complete: $($allPotentialFiles.Count) candidates produced $installationCount installation record(s) for $($finalSortedModules.Keys.Count) module(s) in $([math]::Round($totalFunctionDuration.TotalSeconds, 2)) seconds; skipped $($skippedFiles.Count) support file(s), used fallback metadata for $($fallbackFiles.Count), and could not parse $($failedFiles.Count)." -Level $inventoryLevel
return $finalSortedModules
}
#endregion Get-ModuleInfo
#region Get-ModuleUpdateStatus
function Get-ModuleUpdateStatus {
<#
.SYNOPSIS
Finds newer module versions in registered PSResource repositories.
.DESCRIPTION
Fetches stable and prerelease metadata in parallel, applying repository exclusions
separately for each module. It compares the online versions with the local inventory
and returns one record for each module that has an update.
.PARAMETER ModuleInventory
Module inventory returned by Get-ModuleInfo.
.PARAMETER Repositories
Registered PSResource repositories to query, in priority order.
.PARAMETER ThrottleLimit
Maximum number of concurrent repository lookups and comparisons.
.PARAMETER TimeoutSeconds
Hard time limit, in seconds, for the complete online lookup operation.
.PARAMETER FindModuleTimeoutSeconds
Soft time budget, in seconds, for repository queries for one module.
.PARAMETER BlackList
Maps module names to excluded repositories. Use '*' to exclude a module completely.
.PARAMETER MatchAuthor
Reports an update only when normalized local and repository author names match.
.INPUTS
None.
.OUTPUTS
System.Management.Automation.PSCustomObject. Each record contains the module name,
repository, local and online versions, prerelease data, and outdated installations.
.EXAMPLE
$updates = Get-ModuleUpdateStatus -ModuleInventory $inventory -Repositories 'PSGallery' -MatchAuthor
Checks PSGallery and requires matching author names.
.NOTES
Requires Microsoft.PowerShell.PSResourceGet and network access to the repositories.
.LINK
Find-PSResource
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)][hashtable]$ModuleInventory,
[string[]]$Repositories = @('PSGallery', 'NuGet'),
[int]$ThrottleLimit = ([Environment]::ProcessorCount * 2),
[ValidateRange(1, 3600)][int]$TimeoutSeconds = 30,
[ValidateRange(1, 60)][int]$FindModuleTimeoutSeconds = 10,
[hashtable]$BlackList = @{},
[switch]$MatchAuthor
)
if ($PSVersionTable.PSVersion.Major -lt 7) {
New-Log "This function requires PowerShell 7 or later. Current version: $($PSVersionTable.PSVersion)" -Level ERROR
return
}
$allModuleNames = $ModuleInventory.Keys | Where-Object { $_ -and $_.Trim() } | Sort-Object -Unique
if ($allModuleNames.Count -eq 0) {
New-Log "Module inventory is empty. Nothing to check."
return @()
}
$moduleDataArray = @()
foreach ($moduleNameInLoop in $allModuleNames) {
$localModulesInput = $ModuleInventory[$moduleNameInLoop]
if ($localModulesInput -is [PSCustomObject]) {
$localModulesInput = @($localModulesInput)
}
$parsedVersions = $localModulesInput | Where-Object { $_ -and ($_.PSObject.Properties.Name -contains 'ModuleVersion' -or $_.PSObject.Properties.Name -contains 'ModuleVersionString') -and $_.PSObject.Properties.Name -contains 'BasePath' } | ForEach-Object {
[PSCustomObject]@{
ModuleVersion = $_.ModuleVersion
ModuleVersionString = $_.ModuleVersionString
PreReleaseLabel = $_.PreReleaseLabel
BasePath = $_.BasePath
IsPreRelease = $_.IsPrerelease
Author = $_.Author
}
}
if ($parsedVersions.Count -gt 0) {
$highestLocalVersionInstall = $parsedVersions | Sort-Object -Property @{E = { $_.ModuleVersion }; Descending = $true }, @{E = { $_.IsPreRelease }; Ascending = $true } | Select-Object -First 1
$moduleDataArray += [PSCustomObject]@{
ModuleName = $moduleNameInLoop
HighestLocalInstall = $highestLocalVersionInstall
AllParsedVersions = $parsedVersions
}
}
}
$validModuleCountForProcessing = $moduleDataArray.Count
if ($validModuleCountForProcessing -eq 0) {
New-Log "No valid modules remaining after pre-processing local inventory." -Level WARNING
return @()
}
New-Log "Prepared $validModuleCountForProcessing modules from local inventory." -Level VERBOSE
New-Log "Starting online version pre-fetching for $($moduleDataArray.Count) modules (Throttle: $ThrottleLimit, max ${TimeoutSeconds}s)..."
$overallOperationStartTime = Get-Date
$onlineModuleVersionsCache = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new()
$NewLogDef = ${function:New-Log}.ToString()
# Fetch metadata concurrently and recalculate repository exclusions for each module.
$moduleDataArray | ForEach-Object -ThrottleLimit $ThrottleLimit -TimeoutSeconds $TimeoutSeconds -Parallel {
$moduleNameToFetch = $_.ModuleName
${function:New-Log} = $using:NewLogDef
$VerbosePreference = $using:VerbosePreference
$allRepositories = @($using:Repositories)
$blackList = $using:BlackList
$perModuleBudget = $using:FindModuleTimeoutSeconds
$cache = $using:onlineModuleVersionsCache
$currentRepositories = $allRepositories
if ($blackList -and $blackList.ContainsKey($moduleNameToFetch)) {
$setting = $blackList[$moduleNameToFetch]
if ($setting -eq '*') {
$cache[$moduleNameToFetch] = [pscustomobject]@{ ModuleName = $moduleNameToFetch; Stable = $null; PreRelease = $null; ErrorFetching = $null; Skipped = $true }
New-Log "[$moduleNameToFetch] Pre-fetch: Blacklisted ('*'). Skipping online check." -Level VERBOSE
return
}
elseif ($setting -is [array]) { $currentRepositories = @($allRepositories | Where-Object { $setting -notcontains $_ }) }
elseif ($setting -is [string]) { $currentRepositories = @($allRepositories | Where-Object { $_ -ne $setting }) }
}
if (@($currentRepositories).Count -eq 0) {
$cache[$moduleNameToFetch] = [pscustomobject]@{ ModuleName = $moduleNameToFetch; Stable = $null; PreRelease = $null; ErrorFetching = $null; Skipped = $true }
New-Log "[$moduleNameToFetch] Pre-fetch: No repositories left to check after blacklist exclusion. Skipping." -Level VERBOSE
return
}
$stableResult = $null
$prereleaseResult = $null
$fetchError = $null
$swModule = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($repo in $currentRepositories) {
if ($swModule.Elapsed.TotalSeconds -gt $perModuleBudget) { $fetchError = "Per-module time budget (${perModuleBudget}s) exceeded during stable search."; break }
try {
$found = Find-PSResource -Name $moduleNameToFetch -Repository $repo -ErrorAction SilentlyContinue -Verbose:$false | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($found) { $stableResult = $found; break }
}
catch { $fetchError = "Stable search error in '$repo': $($_.Exception.Message)" }
}
$prereleaseRepos = if ($stableResult) { @($stableResult.Repository) } else { $currentRepositories }
foreach ($repo in $prereleaseRepos) {
if ($swModule.Elapsed.TotalSeconds -gt $perModuleBudget) { $fetchError = (@($fetchError, "Per-module time budget exceeded during prerelease search.") -join '; ').Trim('; ', ' '); break }
try {
$found = Find-PSResource -Name $moduleNameToFetch -Prerelease -Repository $repo -ErrorAction SilentlyContinue -Verbose:$false
| Where-Object { $_.IsPrerelease } | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($found) { $prereleaseResult = $found; break }
}
catch { $fetchError = (@($fetchError, "Prerelease search error in '$repo': $($_.Exception.Message)") -join '; ').Trim('; ', ' ') }
}
$cache[$moduleNameToFetch] = [pscustomobject]@{
ModuleName = $moduleNameToFetch
Stable = $stableResult
PreRelease = $prereleaseResult
ErrorFetching = $fetchError
Skipped = $false
}
}
$preFetchTimeouts = 0
foreach ($moduleEntry in $moduleDataArray) {
if (-not $onlineModuleVersionsCache.ContainsKey($moduleEntry.ModuleName)) {
New-Log "[$($moduleEntry.ModuleName)] No pre-fetched data found (timed out or stage cap reached). Marking as error." -Level WARNING
$onlineModuleVersionsCache[$moduleEntry.ModuleName] = [pscustomobject]@{
ModuleName = $moduleEntry.ModuleName
Stable = $null
PreRelease = $null
ErrorFetching = "Data not found in pre-fetch cache (timeout)."
Skipped = $false
}
$preFetchTimeouts++
}
}
$prefetchSync = @{ timeouts = $preFetchTimeouts; completed = ($onlineModuleVersionsCache.Count - $preFetchTimeouts); total = $moduleDataArray.Count }
$preFetchDuration = (Get-Date) - $overallOperationStartTime
$results = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
$comparisonErrors = [System.Collections.Concurrent.ConcurrentBag[string]]::new()
$NewLogDef = ${function:New-Log}.ToString()
$CompareModuleVersionDef = ${function:Compare-ModuleVersion}.ToString()
$moduleDataArray | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel {
$script:ErrorActionPreference = 'Continue'
$moduleData = $_
$moduleName = $moduleData.ModuleName
$comparisonErrors = $using:comparisonErrors
$VerbosePreference = $using:VerbosePreference
${function:New-Log} = $using:NewLogDef
${function:Compare-ModuleVersion} = $using:CompareModuleVersionDef
$results = $using:results
$matchAuthor = $using:MatchAuthor.IsPresent
$onlineCache = $using:onlineModuleVersionsCache
try {
$highestLocalInstall = $moduleData.HighestLocalInstall
if (-not $highestLocalInstall) {
New-Log "[$moduleName] Pre-processed HighestLocalInstall object missing. Skipping." -Level WARNING
$comparisonErrors.Add("$moduleName`: missing local version data")
return
}
$onlineModuleData = $null
if (-not $onlineCache.TryGetValue($moduleName, [ref]$onlineModuleData)) {
New-Log "[$moduleName] Could not retrieve pre-fetched data from cache. Skipping." -Level WARNING
$comparisonErrors.Add("$moduleName`: lookup cache entry missing")
return
}
if ($onlineModuleData.Skipped -or (-not $onlineModuleData.Stable -and -not $onlineModuleData.PreRelease -and $onlineModuleData.ErrorFetching)) {
if ($onlineModuleData.Skipped) {
New-Log "[$moduleName] Skipped by repository exclusion." -Level VERBOSE
}
else {
$comparisonErrors.Add("$moduleName`: $($onlineModuleData.ErrorFetching)")
New-Log "[$moduleName] Repository lookup failed: $($onlineModuleData.ErrorFetching)" -Level WARNING
}
return
}
$stableModule = $onlineModuleData.Stable
$preReleaseModule = $onlineModuleData.PreRelease
$galleryModule = $null
if ($stableModule -and $preReleaseModule) {
$stableVerStr = $stableModule.Version.ToString()
$prereleaseVerStr = $preReleaseModule.Version.ToString()
$prereleaseLbl = $preReleaseModule.PSObject.Properties['PreRelease'].Value
$fullPrereleaseVerStr = if (-not [string]::IsNullOrEmpty($prereleaseLbl)) { "$prereleaseVerStr-$prereleaseLbl" } else { $prereleaseVerStr }
try {
$isPreReleaseNewer = Compare-ModuleVersion -VersionA $stableVerStr -VersionB $fullPrereleaseVerStr -ReturnBoolean
$galleryModule = if ($isPreReleaseNewer) { $preReleaseModule } else { $stableModule }
}
catch {
$galleryModule = $stableModule
$comparisonErrors.Add("$moduleName`: could not compare stable and prerelease versions")
New-Log "[$moduleName] Could not compare stable '$stableVerStr' with prerelease '$fullPrereleaseVerStr'; using stable" -Level ERROR
}
}
elseif ($preReleaseModule) {
$galleryModule = $preReleaseModule
}
elseif ($stableModule) {
$galleryModule = $stableModule
}
if (-not $galleryModule) {
return
}
[string]$latestOnlineStr = if ($galleryModule.PSObject.Properties['PreRelease'].Value) {
"$($galleryModule.Version)-$($galleryModule.PSObject.Properties['PreRelease'].Value)".Trim()
}
else {
"$($galleryModule.Version)".Trim()
}
[string]$highestLocalStr = if ($highestLocalInstall.IsPrerelease -and $highestLocalInstall.PreReleaseLabel) {
"$($highestLocalInstall.ModuleVersion)-$($highestLocalInstall.PreReleaseLabel)"
}
else {
"$($highestLocalInstall.ModuleVersion)"
}
if ([string]::IsNullOrWhiteSpace($latestOnlineStr) -or [string]::IsNullOrWhiteSpace($highestLocalStr)) {
New-Log "[$moduleName] Invalid online ('$latestOnlineStr') or local ('$highestLocalStr') version string. Skipping." -Level WARNING
$comparisonErrors.Add("$moduleName`: invalid version data")
return
}
$needsOverallUpdate = $false
try {
if (Compare-ModuleVersion -VersionA $highestLocalStr -VersionB $latestOnlineStr -ReturnBoolean) {
$needsOverallUpdate = $true
}
}
catch {
New-Log "[$moduleName] Error comparing versions $highestLocalStr and $latestOnlineStr." -Level ERROR
$comparisonErrors.Add("$moduleName`: version comparison failed")
return
}
if ($needsOverallUpdate -and $matchAuthor) {
$localAuthor = $highestLocalInstall.Author
$galleryAuthor = $galleryModule.Author
$authorsMatch = $false
$normalizedLocalAuthor = [Regex]::Replace([string]$localAuthor, '[^a-zA-Z0-9]', '')
$normalizedGalleryAuthor = [Regex]::Replace([string]$galleryAuthor, '[^a-zA-Z0-9]', '')
if ($normalizedLocalAuthor -and $normalizedGalleryAuthor -and $normalizedGalleryAuthor -eq $normalizedLocalAuthor) {
$authorsMatch = $true
}
if (-not $authorsMatch) {
New-Log "[$moduleName] Skipping update: -MatchAuthor specified and authors do not match (Local: '$localAuthor', Online: '$galleryAuthor')." -Level VERBOSE
$needsOverallUpdate = $false
}
}
if ($needsOverallUpdate) {
$outdatedInstallationsDetailed = @()
$allLocalInstalls = $moduleData.AllParsedVersions
$installsByPath = $allLocalInstalls | Group-Object -Property BasePath
foreach ($pathGroup in $installsByPath) {
$versionsInThisPath = $pathGroup.Group
$latestOnlineVersionFoundInThisPath = $false
foreach ($installedVersionEntry in $versionsInThisPath) {
if ($installedVersionEntry.ModuleVersionString -eq $latestOnlineStr) {
$latestOnlineVersionFoundInThisPath = $true; break
}
}
if (-not $latestOnlineVersionFoundInThisPath) {
foreach ($outdatedInstall in $versionsInThisPath) {
$outdatedInstallationsDetailed += [PSCustomObject]@{
Path = $outdatedInstall.BasePath
InstalledVersion = $outdatedInstall.ModuleVersionString
}
}
}
}
if ($outdatedInstallationsDetailed.Count -gt 0) {
$uniqueOutdatedModules = $outdatedInstallationsDetailed | Sort-Object Path, InstalledVersion -Unique
$resultObject = [PSCustomObject]@{
ModuleName = $moduleName
Repository = $galleryModule.Repository
IsPreview = if ($galleryModule.PSObject.Properties['PreRelease'].Value) { $true } else { $false }
PreReleaseVersion = $galleryModule.PSObject.Properties['PreRelease'].Value
HighestLocalVersion = $highestLocalInstall.ModuleVersion
LatestVersion = [version]($galleryModule.Version.ToString() -replace '-.*$', '')
LatestVersionString = $latestOnlineStr
OutdatedModules = $uniqueOutdatedModules
Author = $highestLocalInstall.Author
GalleryAuthor = $galleryModule.Author
}
$results.Add($resultObject)
New-Log "[$moduleName] Update found: Local '$highestLocalStr' -> Online '$latestOnlineStr'. $($uniqueOutdatedModules.Count) outdated paths." -Level SUCCESS
}
else {
New-Log "[$moduleName] Version '$latestOnlineStr' is newer, but no installation path requiring it was found." -Level WARNING
}
}
}
catch {
$comparisonErrors.Add("$moduleName`: $($_.Exception.Message)")
New-Log "[$moduleName] Unhandled comparison error." -Level ERROR
}
}
$moduleObjects = @($results)
$finalOverallTime = (Get-Date) - $overallOperationStartTime
$comparisonDuration = $finalOverallTime - $preFetchDuration
$updateCheckLevel = if ($preFetchTimeouts -gt 0 -or $comparisonErrors.Count -gt 0) { 'WARNING' } else { 'SUCCESS' }
New-Log "Update check complete: $validModuleCountForProcessing module(s) checked in $([math]::Round($finalOverallTime.TotalSeconds, 2)) seconds (lookup $([math]::Round($preFetchDuration.TotalSeconds, 2))s, comparison $([math]::Round($comparisonDuration.TotalSeconds, 2))s); found $($moduleObjects.Count) update(s), $preFetchTimeouts timeout(s), and $($comparisonErrors.Count) comparison error(s)." -Level $updateCheckLevel
if ($prefetchSync.timeouts -gt 0) {
New-Log "$($prefetchSync.timeouts) module pre-fetch checks timed out." -Level WARNING
}
if ($comparisonErrors.Count -gt 0) {
New-Log "Comparison errors: $(@($comparisonErrors) -join '; ')" -Level WARNING
}
return $moduleObjects | Sort-Object ModuleName
}
#endregion Get-ModuleUpdateStatus
#region Update-Modules
function Update-Modules {
<#
.SYNOPSIS
Installs available module updates.
.DESCRIPTION
Validates update records and ShouldProcess decisions on the caller thread, installs
approved modules concurrently, and optionally removes older versions sequentially.
Flat module layouts are preserved unless a locked module policy is selected.
.PARAMETER OutdatedModules
Update records returned by Get-ModuleUpdateStatus. Accepts pipeline input.
.PARAMETER Clean
Removes older versions after the new version is installed successfully.
.PARAMETER UseProgressBar
Displays progress while installation results are processed.
.PARAMETER PreRelease
Allows prerelease targets supplied by the input records.
.PARAMETER ReplaceLockedModuleOnReboot
For a locked flat module, stages replacement files and schedules the in-place update
for the next Windows restart.
.PARAMETER AllowVersionedSubfolder
For a locked flat module, installs the update in a versioned subfolder instead of
preserving the flat layout.
.INPUTS
System.Management.Automation.PSCustomObject.
.OUTPUTS
System.Management.Automation.PSCustomObject. Each result reports updated, failed,
cleaned, and pending-reboot paths.
.EXAMPLE
Get-ModuleUpdateStatus -ModuleInventory $inventory |
Update-Modules -Clean -ReplaceLockedModuleOnReboot
Installs updates, cleans older versions, and schedules locked flat modules for restart.
.NOTES
ReplaceLockedModuleOnReboot and AllowVersionedSubfolder are mutually exclusive.
Administrative rights may be required for system module paths and reboot scheduling.
.LINK
Get-ModuleUpdateStatus
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(ValueFromPipeline, Mandatory)][Object[]]$OutdatedModules,
[switch]$Clean,
[switch]$UseProgressBar,
[switch]$PreRelease,
[switch]$ReplaceLockedModuleOnReboot,
[switch]$AllowVersionedSubfolder
)
begin {
if ($ReplaceLockedModuleOnReboot -and $AllowVersionedSubfolder) {
throw "Parameters -ReplaceLockedModuleOnReboot and -AllowVersionedSubfolder are mutually exclusive. Specify at most one (or neither)."
}
$aggregateResults = [System.Collections.Generic.List[object]]::new()
$batchModules = @()
$updateStartTime = Get-Date
}
process {
foreach ($module in $OutdatedModules) {
$batchModules += $module
}
}
end {
if ($batchModules.Count -eq 0) {
New-Log "No modules provided for update. Exiting."
return
}
$total = $batchModules.Count
New-Log "Preparing $total module update(s)..."
$modulesToInstall = [System.Collections.Generic.List[object]]::new()
$current = 0
foreach ($module in $batchModules) {
$moduleName = $module.ModuleName
$current++
[string]$targetVersionString = $($module.LatestVersion)
[version]$latestVer = $null
if ($module.isPreView) {
$parsedTargetVersion = Parse-ModuleVersion -VersionString "$($targetVersionString)-$($module.PreReleaseVersion)" -ErrorAction SilentlyContinue
[string]$preReleaseVersion = $parsedTargetVersion.PreReleaseVersion
}
else {
$parsedTargetVersion = Parse-ModuleVersion -VersionString $targetVersionString -ErrorAction SilentlyContinue
[string]$preReleaseVersion = $null
}
if (-not $parsedTargetVersion -or -not $parsedTargetVersion.ModuleVersion) {
New-Log "[$current/$total] Skipping module [$moduleName]: Could not parse Target Version String '$targetVersionString' using Parse-ModuleVersion. Will skip." -Level WARNING
$aggregateResults.Add([PSCustomObject]@{
ModuleName = $moduleName
NewVersionPreRelease = if ($module.IsPreview) { "$($targetVersionString)-$($module.PreReleaseVersion)" }
NewVersion = $targetVersionString
UpdatedPaths = @()
FailedPaths = @("Version parsing failed: $targetVersionString")
PendingRebootPaths = @()
PendingReboot = $false
OverallSuccess = $false
CleanedPaths = @()
CleanStatus = if ($Clean.IsPresent) { 'NotRun' } else { 'NotRequested' }
})
continue
}
$latestVer = $parsedTargetVersion.ModuleVersion
[string]$baseVerStr = $latestVer.ToString()
$repository = $module.Repository
$installAsPreview = $parsedTargetVersion.IsPrerelease
if ($installAsPreview -and -not $PreRelease.IsPresent) {
New-Log "[$moduleName] Skipping prerelease '$preReleaseVersion'; specify -PreRelease to install it." -Level WARNING
$aggregateResults.Add([PSCustomObject]@{
ModuleName = $moduleName
NewVersionPreRelease = $preReleaseVersion
NewVersion = $baseVerStr
UpdatedPaths = @()
FailedPaths = @('Prerelease updates require -PreRelease')
PendingRebootPaths = @()
PendingReboot = $false
OverallSuccess = $false
CleanedPaths = @()
CleanStatus = if ($Clean.IsPresent) { 'NotRun' } else { 'NotRequested' }
})
continue
}
$outdatedPaths = @($module.OutdatedModules | Where-Object { $null -ne $_.Path } | Select-Object -ExpandProperty Path -Unique | Where-Object { $_ -and (Test-Path $_ -PathType Container -Verbose:$false) })
$outdatedVersions = @($module.OutdatedModules.InstalledVersion | Select-Object -Unique)
if ($outdatedPaths.Count -eq 0) {
New-Log "[$moduleName][$current/$total] Skipping module: No valid outdated base paths found where old versions exist. (Checked: $($module.OutdatedModules.Path -join '; '))." -Level WARNING
$aggregateResults.Add([PSCustomObject]@{
ModuleName = $moduleName
NewVersionPreRelease = if ($module.IsPreview) { $preReleaseVersion }
NewVersion = $baseVerStr
UpdatedPaths = @()
FailedPaths = @("No valid source paths provided or accessible")
PendingRebootPaths = @()
PendingReboot = $false
OverallSuccess = $false
CleanedPaths = @()
CleanStatus = if ($Clean.IsPresent) { 'NotRun' } else { 'NotRequested' }
})
continue
}
New-Log "[$moduleName] Target base paths based on outdated locations: $($outdatedPaths -join '; ')" -Level VERBOSE
$displayVersion = if ($installAsPreview -and $preReleaseVersion) { $preReleaseVersion } else { $targetVersionString }
# ShouldProcess must run before work is dispatched to parallel runspaces.
if ($PSCmdlet.ShouldProcess("$moduleName v$displayVersion", "Install from repository '$repository' to paths: $($outdatedPaths -join ', ')")) {
$modulesToInstall.Add([PSCustomObject]@{
ModuleName = $moduleName