Repository navigation
Expand file tree
/
Copy pathUpdate-Modules.ps1
More file actions
3554 lines (3554 loc) · 173 KB
/
Copy pathUpdate-Modules.ps1
File metadata and controls
3554 lines (3554 loc) · 173 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-07-18
Version: 4.8
- Added an -OnlyCleanUpOldModules parameter set to Update-Modules that skips the update check and cleans old versions from the Get-ModuleInfo inventory ($script:moduleInfo), keeping the highest version per path.
- Added -CleanupBackupPath to back up each old version as <Module>\<Module>_<version>.zip before removal; a failed backup keeps that folder.
- Extended -ReplaceLockedModuleOnReboot to cleanup: locked or access-denied version folders are scheduled for deletion on the next restart via PendingFileRenameOperations.
- Added automatic ACL repair (takeown + icacls with the S-1-5-32-544 SID) and a removal retry for access-denied folders such as the built-in Pester 3.4.0.
- Remove-OutdatedVersions now returns a structured result; failed cleanups report CleanStatus Failed, PartiallySucceeded, or PendingReboot instead of a false NoOldVersions.
- Added FailedCleanPaths, CleanPendingRebootPaths, and BackupPaths to all result objects and extended the cleanup summaries with failed and pending-reboot counts plus a -ReplaceLockedModuleOnReboot hint.
#>
#region Check-PSResourceRepository
function Check-PSResourceRepository {
<#
.SYNOPSIS
Ensures that PSResourceGet and the required repositories are configured.
.DESCRIPTION
Imports Microsoft.PowerShell.PSResourceGet, installing it for all users when
necessary, and idempotently configures only the selected repositories.
The function is intended for PowerShell 7 running as administrator. It emits
exactly one success-stream value: $true when the final configuration is valid,
or $false when setup or verification fails.
.PARAMETER ImportDependencies
Requests an explicit module import. If PSResourceGet is already loaded, the
current session-safe instance is retained because binary modules can't be
hot-reloaded after another version is installed. ForceImport is an alias for
this parameter.
.PARAMETER ForceInstall
Forces Microsoft.PowerShell.PSResourceGet to be installed again before import.
.PARAMETER Repositories
Repository names to configure and verify. Valid values are PSGallery, NuGet,
and NuGetGallery. When omitted, all three repositories are checked.
.OUTPUTS
System.Boolean
.EXAMPLE
$repositoryReady = Check-PSResourceRepository
.EXAMPLE
$repositoryReady = Check-PSResourceRepository -ForceImport
.EXAMPLE
$repos = @('PSGallery', 'NuGet')
$repositoryReady = Check-PSResourceRepository -Repositories $repos
.NOTES
Requires PowerShell 7, administrator rights, and network access when the module
must be installed.
#>
[CmdletBinding()]
[OutputType([bool])]
param (
[Alias('ForceImport')][switch]$ImportDependencies,
[switch]$ForceInstall,
[ValidateNotNullOrEmpty()]
[ValidateSet('PSGallery', 'NuGet', 'NuGetGallery')]
[string[]]$Repositories = @('PSGallery', 'NuGet', 'NuGetGallery')
)
function Test-RepositoryConfiguration {
[OutputType([bool])]
param (
[AllowNull()][psobject]$Repository,
[Parameter(Mandatory)][hashtable]$Definition
)
if ($null -eq $Repository) {
return $false
}
if (-not [bool]$Repository.Trusted -or
[int]$Repository.Priority -ne [int]$Definition.Priority) {
return $false
}
if ($Definition.ContainsKey('Uri')) {
try {
$actualUri = ([uri]$Repository.Uri).AbsoluteUri.TrimEnd('/')
$expectedUri = ([uri]$Definition.Uri).AbsoluteUri.TrimEnd('/')
}
catch {
return $false
}
if ($actualUri -ine $expectedUri) {
return $false
}
}
if ($Definition.ContainsKey('ApiVersion') -and
[string]$Repository.ApiVersion -ine [string]$Definition.ApiVersion) {
return $false
}
return $true
}
$moduleName = 'Microsoft.PowerShell.PSResourceGet'
try {
# Command discovery auto-imports PSResourceGet, which would load its binary assembly before a requested reinstall and make the new assembly impossible to load in-process.
$loadedModule = Get-Module -Name $moduleName | Select-Object -First 1
$resourceCommand = if ($null -ne $loadedModule) {
Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue
}
else {
$null
}
if (-not $ForceInstall -and $null -eq $resourceCommand) {
try {
$importParams = @{
Name = $moduleName
ErrorAction = 'Stop'
Verbose = $false
WarningAction = 'SilentlyContinue'
}
Import-Module @importParams
$loadedModule = Get-Module -Name $moduleName | Select-Object -First 1
$resourceCommand = Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue
}
catch {
New-Log "PSResourceGet could not be imported; installation will be attempted." -Level ERROR
$resourceCommand = $null
}
}
elseif (-not $ForceInstall -and $ImportDependencies -and $null -ne $loadedModule) {
New-Log "PSResourceGet $($loadedModule.Version) is already loaded; retaining the current binary module instance."
}
if ($ForceInstall -or $null -eq $resourceCommand) {
if ($null -eq (Get-Command -Name 'Install-Module' -ErrorAction SilentlyContinue)) {
New-Log 'Install-Module is unavailable, so PSResourceGet cannot be installed.' -Level WARNING
return $false
}
# Install-Module uses the legacy PowerShellGet repository store. Make its PSGallery entry usable for an unattended bootstrap when those commands exist.
if ($null -ne (Get-Command -Name 'Get-PSRepository' -ErrorAction SilentlyContinue)) {
$legacyGallery = Get-PSRepository -Name 'PSGallery' -ErrorAction SilentlyContinue
if ($null -eq $legacyGallery) {
Register-PSRepository -Default -ErrorAction Stop
$legacyGallery = Get-PSRepository -Name 'PSGallery' -ErrorAction Stop
}
if ($legacyGallery.InstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted -ErrorAction Stop
}
}
New-Log "Installing $moduleName for all users..."
$installParams = @{
Name = $moduleName
Repository = 'PSGallery'
Scope = 'AllUsers'
Force = $true
AllowClobber = $true
AcceptLicense = $true
Confirm = $false
ErrorAction = 'Stop'
PassThru = $true
Verbose = $false
}
$installedResource = Install-Module @installParams
$sessionModule = Get-Module -Name $moduleName | Select-Object -First 1
if ($null -ne $sessionModule) {
# A .NET assembly can't be replaced inside a running pwsh process. Keep
# using the functional version that is already loaded; the installed
# version will be selected automatically by the next pwsh process.
$resourceCommand = Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue
$installedVersion = if ($null -ne $installedResource.Version) { $installedResource.Version } else { 'unknown' }
New-Log "Installation completed. Continuing with loaded PSResourceGet $($sessionModule.Version); installed version $installedVersion will be used in new PowerShell sessions."
}
else {
Import-Module -Name $moduleName -ErrorAction Stop -Verbose:$false -WarningAction SilentlyContinue
$resourceCommand = Get-Command -Name 'Get-PSResourceRepository' -ErrorAction SilentlyContinue
}
}
if ($null -eq $resourceCommand) {
New-Log 'PSResourceGet was imported, but Get-PSResourceRepository is unavailable.' -Level WARNING
return $false
}
$requiredCommands = @(
'Get-PSResourceRepository'
'Register-PSResourceRepository'
'Set-PSResourceRepository'
)
foreach ($commandName in $requiredCommands) {
if ($null -eq (Get-Command -Name $commandName -ErrorAction SilentlyContinue)) {
New-Log "Required PSResourceGet command '$commandName' is unavailable." -Level WARNING
return $false
}
}
$repositoryDefinitions = @(
@{
Name = 'PSGallery'
Priority = 30
PSGallery = $true
}
@{
Name = 'NuGetGallery'
Uri = 'https://api.nuget.org/v3/index.json'
Priority = 40
ApiVersion = 'V3'
}
@{
Name = 'NuGet'
Uri = 'https://www.nuget.org/api/v2'
Priority = 50
ApiVersion = 'V2'
}
)
$requestedRepositories = @($Repositories | Select-Object -Unique)
$repositoriesToCheck = @($repositoryDefinitions | Where-Object { $_.Name -in $requestedRepositories })
New-Log "PSResourceGet is available. Checking repositories: $($repositoriesToCheck.Name -join ', ')..."
foreach ($definition in $repositoriesToCheck) {
$repository = Get-PSResourceRepository -Name $definition.Name -ErrorAction SilentlyContinue
if ($null -eq $repository) {
if ($definition.PSGallery) {
Register-PSResourceRepository -PSGallery -Trusted -Priority $definition.Priority -Confirm:$false -ErrorAction Stop
}
else {
$registerParams = @{
Name = $definition.Name
Uri = $definition.Uri
Priority = $definition.Priority
ApiVersion = $definition.ApiVersion
Trusted = $true
Confirm = $false
ErrorAction = 'Stop'
}
Register-PSResourceRepository @registerParams
}
New-Log "Registered repository '$($definition.Name)'." -Level SUCCESS
}
elseif (-not (Test-RepositoryConfiguration -Repository $repository -Definition $definition)) {
$setParams = @{
Name = $definition.Name
Priority = $definition.Priority
Trusted = $true
Confirm = $false
ErrorAction = 'Stop'
}
if (-not $definition.PSGallery) {
$setParams.Uri = $definition.Uri
$setParams.ApiVersion = $definition.ApiVersion
}
Set-PSResourceRepository @setParams
New-Log "Updated repository '$($definition.Name)'." -Level SUCCESS
}
else {
New-Log "Repository '$($definition.Name)' is already configured correctly."
}
$verifiedRepository = Get-PSResourceRepository -Name $definition.Name -ErrorAction SilentlyContinue
if (-not (Test-RepositoryConfiguration -Repository $verifiedRepository -Definition $definition)) {
New-Log "Repository '$($definition.Name)' failed final verification." -Level WARNING
return $false
}
}
New-Log 'All selected repositories are configured and verified.' -Level SUCCESS
return $true
}
catch {
New-Log "PSResource repository setup failed." -Level ERROR
return $false
}
}
#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/nuspec 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/nuspec 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 -ErrorAction Stop) | Where-Object { $_.Name -match '^(PSGetModuleInfo\.xml|.*\.nuspec)$' }
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) {
New-Log "Skipping resource file '$filePath'." -Level VERBOSE
$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 {
New-Log "Get-ManifestVersionInfo failed for '$filePath': $($_.Exception.Message)" -Level VERBOSE
$manifestInfoObj = $null
$usedFallback = $true
}
}
if (-not $manifestInfoObj) {
$usedFallback = $true
try {
$manifestInfoObj = Get-ManifestVersionInfo -ModuleFilePath $filePath -ErrorAction Stop -WarningAction SilentlyContinue
}
catch {
New-Log "Fallback Get-ManifestVersionInfo failed for '$filePath': $($_.Exception.Message)" -Level VERBOSE
$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) {
New-Log "Found module '$($mInfo.ModuleName)' version '$($mInfo.ModuleVersionString)' at '$($mInfo.BasePath)'." -Level VERBOSE
$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) {
New-Log "No valid module data could be extracted from manifest '$filePath'." -Level VERBOSE
$failedFiles.Add($filePath)
}
}
elseif ($fileExtension -in @('.xml', '.nuspec')) {
$xmlInfo = Get-ModuleInfoFromXml -XmlFilePath $filePath -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if ($xmlInfo -and $xmlInfo.ModuleName -and $xmlInfo.ModuleVersion) {
New-Log "Found module '$($xmlInfo.ModuleName)' version '$($xmlInfo.ModuleVersionString)' at '$($xmlInfo.BasePath)'." -Level VERBOSE
$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 {
New-Log "No valid module data could be extracted from XML file '$filePath'." -Level VERBOSE
$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 OnlineCacheMinutes
Lifetime of successful online lookup metadata in minutes. The default is 30;
specify 0 to disable the persistent cache.
.PARAMETER OnlineCachePath
JSON file used for the persistent online lookup cache.
.PARAMETER LookupRetryCount
Number of targeted retries for modules that did not finish within the main stage.
.PARAMETER RetryTimeoutSeconds
Hard time limit, in seconds, for each targeted retry stage.
.PARAMETER ForceOnlineRefresh
Ignores existing persistent cache entries for this run.
.PARAMETER BlackList
Maps module names to excluded repositories. Use '*' to exclude all repositories for a module. The default is an empty hashtable.
.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', 'NuGetGallery'),
[int]$ThrottleLimit = ([Environment]::ProcessorCount * 2),
[ValidateRange(1, 3600)][int]$TimeoutSeconds = 60,
[ValidateRange(1, 60)][int]$FindModuleTimeoutSeconds = 15,
[ValidateRange(0, 1440)][int]$OnlineCacheMinutes = 30,
[ValidateNotNullOrEmpty()][string]$OnlineCachePath = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Temp\Update-Modules\OnlineVersionCache.json'),
[ValidateRange(0, 3)][int]$LookupRetryCount = 1,
[ValidateRange(1, 300)][int]$RetryTimeoutSeconds = 10,
[switch]$ForceOnlineRefresh,
[hashtable]$BlackList = @{},
[switch]$MatchAuthor
)
function ConvertTo-OnlineCacheResource {
param ([AllowNull()][psobject]$Resource)
if ($null -eq $Resource) { return $null }
return [pscustomobject]@{
Version = [string]$Resource.Version
Repository = [string]$Resource.Repository
Author = [string]$Resource.Author
PreRelease = if ($Resource.PSObject.Properties['PreRelease']) { [string]$Resource.PreRelease } else { $null }
IsPrerelease = if ($Resource.PSObject.Properties['IsPrerelease']) { [bool]$Resource.IsPrerelease } else { $false }
}
}
$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
New-Log "Module '$moduleNameInLoop' has $($parsedVersions.Count) local installation(s); highest version is '$($highestLocalVersionInstall.ModuleVersionString)'." -Level VERBOSE
$moduleDataArray += [PSCustomObject]@{
ModuleName = $moduleNameInLoop
HighestLocalInstall = $highestLocalVersionInstall
AllParsedVersions = $parsedVersions
}
}
else {
New-Log "Module '$moduleNameInLoop' has no valid version data and will be skipped." -Level WARNING
}
}
$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
$overallOperationStartTime = Get-Date
$onlineModuleVersionsCache = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new([System.StringComparer]::OrdinalIgnoreCase)
$normalizedRepositories = @($Repositories | ForEach-Object { ([string]$_).ToLowerInvariant() })
$normalizedBlackList = @($BlackList.GetEnumerator() | Sort-Object { [string]$_.Key } | ForEach-Object {
$normalizedValues = @($_.Value | ForEach-Object { ([string]$_).ToLowerInvariant() } | Sort-Object)
"$(([string]$_.Key).ToLowerInvariant())=$($normalizedValues -join ',')"
})
$onlineCacheConfigurationKey = "$($normalizedRepositories -join '|')::$($normalizedBlackList -join ';')"
$moduleNamesToCheck = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
foreach ($moduleData in $moduleDataArray) { [void]$moduleNamesToCheck.Add($moduleData.ModuleName) }
$cacheHits = 0
if ($OnlineCacheMinutes -gt 0 -and -not $ForceOnlineRefresh.IsPresent -and (Test-Path -LiteralPath $OnlineCachePath -PathType Leaf)) {
try {
$cacheDocument = Get-Content -LiteralPath $OnlineCachePath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
if ([int]$cacheDocument.SchemaVersion -eq 2 -and [string]$cacheDocument.ConfigurationKey -ceq $onlineCacheConfigurationKey) {
$cacheCutoffUtc = [DateTime]::UtcNow.AddMinutes(-$OnlineCacheMinutes)
foreach ($cacheEntry in @($cacheDocument.Entries)) {
if ($null -eq $cacheEntry -or -not $moduleNamesToCheck.Contains([string]$cacheEntry.ModuleName)) { continue }
try { $cachedAtUtc = [DateTime]::new([long]$cacheEntry.CachedAtUtcTicks, [DateTimeKind]::Utc) }
catch { continue }
if ($cachedAtUtc -lt $cacheCutoffUtc) { continue }
New-Log "Online lookup cache hit for module '$($cacheEntry.ModuleName)' (cached at $($cachedAtUtc.ToString('u')))." -Level VERBOSE
$onlineModuleVersionsCache[[string]$cacheEntry.ModuleName] = [pscustomobject]@{
ModuleName = [string]$cacheEntry.ModuleName
Stable = $cacheEntry.Stable
PreRelease = $cacheEntry.PreRelease
ErrorFetching = $null
Skipped = $false
CachedAtUtc = $cachedAtUtc
}
$cacheHits++
}
}
else {
New-Log "Online lookup cache configuration changed; ignoring existing entries." -Level VERBOSE
}
}
catch {
New-Log "Online lookup cache could not be read and will be rebuilt." -Level ERROR
}
}
elseif ($ForceOnlineRefresh.IsPresent) {
New-Log "Forcing a fresh online lookup; existing cache entries are being ignored." -Level VERBOSE
}
$modulesPendingLookup = @($moduleDataArray | Where-Object { -not $onlineModuleVersionsCache.ContainsKey($_.ModuleName) })
New-Log "Online lookup cache: $cacheHits hit(s), $($modulesPendingLookup.Count) lookup(s) required (TTL: $OnlineCacheMinutes minute(s))." -Level VERBOSE
$NewLogDef = ${function:New-Log}.ToString()
# Run lookup stages as background parallel jobs so timed-out pipelines can be stopped and drained quietly.
for ($lookupAttempt = 0; $lookupAttempt -le $LookupRetryCount -and $modulesPendingLookup.Count -gt 0; $lookupAttempt++) {
$stageTimeoutSeconds = if ($lookupAttempt -eq 0) { $TimeoutSeconds } else { $RetryTimeoutSeconds }
if ($lookupAttempt -eq 0) {
New-Log "Starting online version pre-fetching for $($modulesPendingLookup.Count) module(s) (Throttle: $ThrottleLimit, max ${stageTimeoutSeconds}s)..."
}
else {
New-Log "Retrying $($modulesPendingLookup.Count) unfinished module lookup(s), attempt $lookupAttempt of $LookupRetryCount (max ${stageTimeoutSeconds}s)..." -Level VERBOSE
}
$lookupJob = $null
$stageTimedOut = $false
try {
$lookupJob = $modulesPendingLookup | ForEach-Object -ThrottleLimit $ThrottleLimit -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
CachedAtUtc = [DateTime]::UtcNow
}
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
CachedAtUtc = [DateTime]::UtcNow
}
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) {
New-Log "[$moduleNameToFetch] Pre-fetch: Found stable version '$($found.Version)' in repository '$repo'." -Level VERBOSE
$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) {
New-Log "[$moduleNameToFetch] Pre-fetch: Found prerelease version '$($found.Version)' in repository '$repo'." -Level VERBOSE
$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
CachedAtUtc = [DateTime]::UtcNow
}
} -AsJob
$null = Wait-Job -Job $lookupJob -Timeout $stageTimeoutSeconds -ErrorAction SilentlyContinue
if ($lookupJob.State -in @('Running', 'NotStarted')) {
$stageTimedOut = $true
Stop-Job -Job $lookupJob -ErrorAction SilentlyContinue 2>$null
}
elseif ($lookupJob.State -ne 'Completed') {
New-Log "Online lookup job ended in state '$($lookupJob.State)'. Unfinished modules will be retried or reported." -Level WARNING
}
}
catch {
New-Log "Online lookup job failed." -Level ERROR
if ($null -ne $lookupJob -and $lookupJob.State -in @('Running', 'NotStarted')) {
Stop-Job -Job $lookupJob -ErrorAction SilentlyContinue 2>$null
}
}
finally {
if ($null -ne $lookupJob) {
Receive-Job -Job $lookupJob -ErrorAction SilentlyContinue -WarningAction SilentlyContinue 2>$null | Out-Null
Remove-Job -Job $lookupJob -Force -ErrorAction SilentlyContinue 2>$null
}
}
$modulesPendingLookup = @($moduleDataArray | Where-Object { -not $onlineModuleVersionsCache.ContainsKey($_.ModuleName) })
if ($stageTimedOut -and $modulesPendingLookup.Count -gt 0) {
New-Log "Online lookup stage reached its ${stageTimeoutSeconds}s cap; $($modulesPendingLookup.Count) unfinished module(s) remain." -Level WARNING
}
}
$preFetchTimeouts = 0
foreach ($moduleEntry in $moduleDataArray) {
if (-not $onlineModuleVersionsCache.ContainsKey($moduleEntry.ModuleName)) {
New-Log "[$($moduleEntry.ModuleName)] No pre-fetched data found after all lookup attempts. Marking as error." -Level WARNING
$onlineModuleVersionsCache[$moduleEntry.ModuleName] = [pscustomobject]@{
ModuleName = $moduleEntry.ModuleName
Stable = $null
PreRelease = $null
ErrorFetching = "Data not found after online lookup timeout and retry."
Skipped = $false
CachedAtUtc = [DateTime]::UtcNow
}
$preFetchTimeouts++
}
}
if ($OnlineCacheMinutes -gt 0) {
$tempCachePath = "$OnlineCachePath.$PID.tmp"
try {
$cacheEntries = foreach ($moduleEntry in $moduleDataArray) {
$lookupData = $null
if (-not $onlineModuleVersionsCache.TryGetValue($moduleEntry.ModuleName, [ref]$lookupData)) { continue }
if ($lookupData.Skipped -or -not [string]::IsNullOrWhiteSpace([string]$lookupData.ErrorFetching)) { continue }
$cachedAtUtc = if ($lookupData.PSObject.Properties['CachedAtUtc']) { ([DateTime]$lookupData.CachedAtUtc).ToUniversalTime() } else { [DateTime]::UtcNow }
[pscustomobject]@{
ModuleName = $moduleEntry.ModuleName
CachedAtUtc = $cachedAtUtc.ToString('o')
CachedAtUtcTicks = $cachedAtUtc.Ticks
Stable = ConvertTo-OnlineCacheResource -Resource $lookupData.Stable
PreRelease = ConvertTo-OnlineCacheResource -Resource $lookupData.PreRelease
}
}
$cacheDirectory = Split-Path -Path $OnlineCachePath -Parent
if (-not [string]::IsNullOrWhiteSpace($cacheDirectory) -and -not (Test-Path -LiteralPath $cacheDirectory -PathType Container)) {
$null = New-Item -ItemType Directory -Path $cacheDirectory -Force -ErrorAction Stop
}
$cacheDocumentToSave = [pscustomobject]@{
SchemaVersion = 2
ConfigurationKey = $onlineCacheConfigurationKey
WrittenAtUtc = [DateTime]::UtcNow.ToString('o')
Entries = @($cacheEntries)
}
$cacheDocumentToSave | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $tempCachePath -Encoding utf8 -ErrorAction Stop
Move-Item -LiteralPath $tempCachePath -Destination $OnlineCachePath -Force -ErrorAction Stop
New-Log "Online lookup cache saved with $(@($cacheEntries).Count) successful entry/entries." -Level VERBOSE
}
catch {
New-Log "Online lookup cache could not be saved." -Level ERROR
}
finally {
if (Test-Path -LiteralPath $tempCachePath -PathType Leaf) {
Remove-Item -LiteralPath $tempCachePath -Force -ErrorAction SilentlyContinue
}
}
}
$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) {
New-Log "[$moduleName] No valid online version found. Skipping." -Level WARNING
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)")