-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-AllModule.ps1
More file actions
780 lines (660 loc) · 33.4 KB
/
Copy pathUpdate-AllModule.ps1
File metadata and controls
780 lines (660 loc) · 33.4 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
function Update-AllModule
{
<#
.SYNOPSIS
Updates all installed PowerShell modules to their latest versions.
.DESCRIPTION
This function checks installed PowerShell modules for newer versions in the PowerShell Gallery and
updates only the modules that are actually outdated. Each module is updated individually with proper
error handling and progress reporting. It supports excluding specific modules and can optionally
configure PSGallery trust. Cross-platform compatible with PowerShell 5.1+ on Windows, macOS, and Linux.
.PARAMETER ExcludeModule
Array of module names to exclude from updates.
.PARAMETER IncludeModule
Array of specific module names to include for updates. When specified, only these modules
will be considered for updates. Cannot be used together with ExcludeModule.
.PARAMETER TrustPSGallery
Automatically sets PSGallery installation policy to Trusted if not already configured.
.PARAMETER Force
Forces the update even if a newer version is already installed.
.PARAMETER UseElevation
Automatically elevates privileges when updating modules that require administrator rights.
Only works on Windows platforms. On other platforms, this parameter is ignored.
.PARAMETER SkipPublisherCheck
Skips the publisher check when updating modules. This allows updating modules that have
different digital signatures than the previously installed version.
Requires PowerShellGet 2.0 or later. If using an older version of PowerShellGet,
this parameter will be ignored with a warning message.
WARNING: This bypasses an important security feature. Only use this parameter when you trust
the module source and have verified the update is legitimate. Consider using -WhatIf first
to review what would be updated before applying this parameter.
.PARAMETER Interactive
Prompts the user for each module update, allowing them to choose whether to update each
individual module. This provides fine-grained control over which modules are updated.
.PARAMETER RemoveOldVersions
Removes older installed versions for modules that were successfully updated. This reuses
the Remove-OldModule function so the cleanup behavior stays consistent.
.PARAMETER WhatIf
Shows what modules would be updated without actually updating them.
.EXAMPLE
PS > Update-AllModule
Updates all installed PowerShell modules to their latest versions.
.EXAMPLE
PS > Update-AllModule -IncludeModule @('Pester', 'DailyBackup')
Updates only the specified modules (Pester and DailyBackup).
.EXAMPLE
PS > Update-AllModule -IncludeModule @('Pester') -Interactive -UseElevation
Interactive mode for only the Pester module with automatic privilege elevation.
.EXAMPLE
PS > Update-AllModule -ExcludeModule @('Azure', 'AzureRM') -TrustPSGallery
Updates all modules except Azure and AzureRM, and configures PSGallery as trusted.
.EXAMPLE
PS > Update-AllModule -UseElevation -Verbose
Updates all modules with automatic privilege elevation for modules requiring admin rights.
.EXAMPLE
PS > Update-AllModule -Interactive
Prompts for each module update, allowing the user to choose which modules to update.
.EXAMPLE
PS > Update-AllModule -Interactive -UseElevation
Interactive mode with automatic privilege elevation when needed.
.EXAMPLE
PS > Update-AllModule -UseElevation -SkipPublisherCheck -Verbose
Updates all modules with automatic privilege elevation and skips publisher verification.
WARNING: Only use -SkipPublisherCheck when you trust the module sources.
.EXAMPLE
PS > Update-AllModule -ExcludeModule @('Azure', 'AzureRM') -UseElevation
Updates all modules except Azure and AzureRM, using elevation when needed.
.EXAMPLE
PS > Update-AllModule -Force -Verbose
Forcefully updates all modules with verbose output.
.EXAMPLE
PS > Update-AllModule -RemoveOldVersions
Updates all outdated modules and removes their older installed versions afterward.
.EXAMPLE
PS > Update-AllModule -WhatIf
PS > Get-OutdatedModule | ForEach-Object { Update-Module -Name $_.Name -SkipPublisherCheck }
Safer alternative: First preview what would be updated, then update modules individually
with selective use of -SkipPublisherCheck for better security control.
.EXAMPLE
PS > Update-AllModule -WhatIf
Shows what modules would be updated without actually performing the updates.
.EXAMPLE
PS > Update-AllModule -ExcludeModule @('Azure', 'AzureRM') -WhatIf
Preview what would be updated while excluding specific modules from the update process.
.EXAMPLE
PS > Update-AllModule -Confirm
Updates all modules with interactive confirmation for each operation.
.OUTPUTS
[System.Void]
No output is returned, but progress information is displayed.
.NOTES
- Requires PowerShell 5.1 or later
- Internet connection required to check for updates
- May require elevated permissions on some systems for system-installed modules
- Use -ExcludeModule for problematic modules that fail to update
- Use -IncludeModule to update only specific modules (cannot be used with ExcludeModule)
- Use -UseElevation on Windows to automatically handle privilege elevation
- Use -SkipPublisherCheck to bypass digital signature verification issues (requires PowerShellGet 2.0+)
- Use -Interactive for fine-grained control over which modules to update
- The Invoke-ElevatedCommand function (Functions/SystemAdministration/Invoke-ElevatedCommand.ps1) function must be available for elevation support
- The Remove-OldModule function (Functions/ModuleManagement/Remove-OldModule.ps1) must be available when using -RemoveOldVersions
SECURITY CONSIDERATIONS:
- The -SkipPublisherCheck parameter bypasses PowerShell's built-in security that validates
module publishers. This security feature helps prevent malicious module updates.
- Only use -SkipPublisherCheck for trusted modules from the official PowerShell Gallery
- Consider alternative approaches like updating modules individually to maintain better control
- Always review module changes and changelogs before updating, especially with -SkipPublisherCheck
- Use -WhatIf first to preview what would be updated before using -SkipPublisherCheck
ALTERNATIVE APPROACHES:
- Update modules individually: Update-Module -Name ModuleName -SkipPublisherCheck
- Check module details first: Get-InstalledModule ModuleName | Format-List
- Review publisher changes: Find-Module ModuleName | Format-List Name, Author, CompanyName
- Use PowerShellGet v3+ which has improved publisher validation handling
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/ModuleManagement/Update-AllModule.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/ModuleManagement/Update-AllModule.ps1
.LINK
https://jonlabelle.com/snippets/view/markdown/powershellget-commands
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(SupportsShouldProcess)]
[OutputType([System.Void])]
param(
[Parameter()]
[String[]]$ExcludeModule = @(),
[Parameter()]
[String[]]$IncludeModule = @(),
[Parameter()]
[Switch]$TrustPSGallery,
[Parameter()]
[Switch]$Force,
[Parameter()]
[Switch]$UseElevation,
[Parameter()]
[Switch]$SkipPublisherCheck,
[Parameter()]
[Switch]$Interactive,
[Parameter()]
[Switch]$RemoveOldVersions
)
begin
{
# Helper function to load dependencies on demand
function Import-DependencyIfNeeded
{
param(
[Parameter(Mandatory)]
[String]$FunctionName,
[Parameter(Mandatory)]
[String]$RelativePath
)
if (-not (Get-Command -Name $FunctionName -ErrorAction SilentlyContinue))
{
Write-Verbose "$FunctionName is required - attempting to load it"
# Resolve path from current script location
$dependencyPath = Join-Path -Path $PSScriptRoot -ChildPath $RelativePath
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (Test-Path -Path $dependencyPath -PathType Leaf)
{
try
{
. $dependencyPath
Write-Verbose "Loaded $FunctionName from: $dependencyPath"
}
catch
{
throw "Failed to load required dependency '$FunctionName' from '$dependencyPath': $($_.Exception.Message)"
}
}
else
{
throw "Required function '$FunctionName' could not be found. Expected location: $dependencyPath"
}
}
else
{
Write-Verbose "$FunctionName is already loaded"
}
}
function Get-OutdatedModuleInfo
{
param(
[Parameter(Mandatory)]
[Object[]]$InstalledModules
)
$outdatedModuleInfo = @()
$processedCount = 0
foreach ($module in $InstalledModules)
{
$processedCount++
$percentComplete = if ($InstalledModules.Count -gt 0)
{
($processedCount / $InstalledModules.Count) * 100
}
else
{
0
}
Write-Progress -Activity 'Checking for available updates' -Status "Checking $($module.Name)" -PercentComplete $percentComplete
try
{
$latestModule = Find-Module -Name $module.Name -Repository 'PSGallery' -ErrorAction Stop
if ($latestModule.Version -gt $module.Version)
{
$outdatedModuleInfo += [PSCustomObject]@{
Name = $module.Name
CurrentVersion = $module.Version
AvailableVersion = $latestModule.Version
Module = $module
}
}
else
{
Write-Verbose "$($module.Name) is already up to date"
}
}
catch [System.InvalidOperationException]
{
Write-Warning "Module '$($module.Name)' was not found in PSGallery - skipping"
}
catch
{
Write-Warning "Could not check updates for $($module.Name): $($_.Exception.Message)"
}
}
Write-Progress -Activity 'Checking for available updates' -Completed
return [PSCustomObject[]]$outdatedModuleInfo
}
Write-Verbose 'Starting module update process'
$cancelUpdateProcess = $false
# Check for conflicting parameters
if ($ExcludeModule.Count -gt 0 -and $IncludeModule.Count -gt 0)
{
Write-Error 'Cannot use both ExcludeModule and IncludeModule parameters together. Use one or the other.'
$cancelUpdateProcess = $true
return
}
# Platform detection for elevation support
if ($PSVersionTable.PSVersion.Major -lt 6)
{
# PowerShell 5.1 - Windows only
$script:IsWindowsPlatform = $true
}
else
{
# PowerShell Core - use built-in variables
$script:IsWindowsPlatform = $IsWindows
}
# Check if UseElevation is supported on this platform
if ($UseElevation -and -not $script:IsWindowsPlatform)
{
Write-Warning 'UseElevation parameter is only supported on Windows. Ignoring elevation request.'
$UseElevation = $false
}
# Load Invoke-ElevatedCommand if needed for UseElevation
if ($UseElevation -and $script:IsWindowsPlatform)
{
Import-DependencyIfNeeded -FunctionName 'Invoke-ElevatedCommand' -RelativePath '..\SystemAdministration\Invoke-ElevatedCommand.ps1'
}
if ($RemoveOldVersions)
{
Import-DependencyIfNeeded -FunctionName 'Remove-OldModule' -RelativePath 'Remove-OldModule.ps1'
}
# Check PowerShellGet version for SkipPublisherCheck compatibility
$powerShellGetModule = Get-Module PowerShellGet -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
$supportsSkipPublisherCheck = $powerShellGetModule -and $powerShellGetModule.Version -ge [Version]'2.0.0'
# Show security warning for SkipPublisherCheck
if ($SkipPublisherCheck)
{
if (-not $supportsSkipPublisherCheck)
{
Write-Host "ERROR: SkipPublisherCheck parameter requires PowerShellGet 2.0 or later. Current version: $($powerShellGetModule.Version)" -ForegroundColor Red
Write-Host ''
Write-Host 'To update PowerShellGet:' -ForegroundColor Yellow
Write-Host ' Install-Module PowerShellGet -Force -AllowClobber' -ForegroundColor Cyan
Write-Host ' Restart PowerShell, then try again' -ForegroundColor Cyan
Write-Host ''
Write-Host 'To update Pester manually (common issue):' -ForegroundColor Yellow
Write-Host ' Uninstall-Module Pester -Force -AllVersions' -ForegroundColor Cyan
Write-Host ' Install-Module Pester -Force -Scope CurrentUser' -ForegroundColor Cyan
throw "SkipPublisherCheck requires PowerShellGet 2.0+. Current: $($powerShellGetModule.Version)"
}
else
{
Write-Warning 'SkipPublisherCheck bypasses module publisher verification - a security feature that helps prevent malicious updates. Only proceed if you trust the module sources.'
if (-not $WhatIfPreference -and $Host.UI.RawUI -and [Environment]::UserInteractive)
{
$response = Read-Host 'Do you want to continue with publisher check disabled? (y/N)'
if ($response -notmatch '^[Yy]([Ee][Ss])?$')
{
Write-Host 'Operation cancelled by user.' -ForegroundColor Yellow
$cancelUpdateProcess = $true
return
}
}
}
}
# Configure PSGallery trust if requested
if ($TrustPSGallery)
{
try
{
$repo = Get-PSRepository -Name PSGallery -ErrorAction Stop
if ($repo.InstallationPolicy -ne 'Trusted')
{
if ($PSCmdlet.ShouldProcess('PSGallery repository', 'Set installation policy to Trusted'))
{
Write-Host 'Configuring PSGallery as trusted repository...' -ForegroundColor Cyan
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
Write-Verbose 'PSGallery configured as trusted'
}
}
else
{
Write-Verbose 'PSGallery already configured as trusted'
}
}
catch
{
Write-Error "Failed to configure PSGallery: $($_.Exception.Message)"
$cancelUpdateProcess = $true
return
}
}
}
process
{
if ($cancelUpdateProcess)
{
Write-Verbose 'Module update process cancelled before execution'
return
}
try
{
# Get all installed modules
Write-Host 'Retrieving installed modules...' -ForegroundColor Cyan
$allInstalledModules = @(Get-InstalledModule)
# Apply include/exclude filtering
if ($IncludeModule.Count -gt 0)
{
$installedModules = $allInstalledModules | Where-Object { $_.Name -in $IncludeModule }
if ($installedModules.Count -lt $IncludeModule.Count)
{
$notFound = $IncludeModule | Where-Object { $_ -notin $installedModules.Name }
foreach ($missing in $notFound)
{
Write-Warning "Module '$missing' specified in IncludeModule is not installed"
}
}
}
elseif ($ExcludeModule.Count -gt 0)
{
$installedModules = $allInstalledModules | Where-Object { $_.Name -notin $ExcludeModule }
}
else
{
$installedModules = $allInstalledModules
}
$installedModules = @($installedModules)
if (-not $installedModules -or $installedModules.Count -eq 0)
{
Write-Host 'No modules found to update.' -ForegroundColor Yellow
return
}
Write-Host 'Checking for available updates...' -ForegroundColor Cyan
$outdatedModules = @(Get-OutdatedModuleInfo -InstalledModules $installedModules)
if ($outdatedModules.Count -eq 0)
{
Write-Host 'No modules with available updates were found.' -ForegroundColor Green
return
}
Write-Host "Found $($outdatedModules.Count) module(s) with available updates" -ForegroundColor Yellow
if ($Interactive)
{
Write-Host "Found $($outdatedModules.Count) module(s) with available updates:" -ForegroundColor Yellow
foreach ($outdated in $outdatedModules)
{
Write-Host " - $($outdated.Name): $($outdated.CurrentVersion) ~> $($outdated.AvailableVersion)" -ForegroundColor Cyan
}
Write-Host ''
}
$modulesToProcess = @($outdatedModules)
# Check if this is a WhatIf operation
if ($WhatIfPreference)
{
Write-Host 'WhatIf: The following modules would be updated:' -ForegroundColor Yellow
foreach ($moduleInfo in $modulesToProcess)
{
Write-Host " - $($moduleInfo.Name): $($moduleInfo.CurrentVersion) ~> $($moduleInfo.AvailableVersion)" -ForegroundColor Cyan
}
if ($RemoveOldVersions)
{
Write-Host ''
Write-Host 'WhatIf: Older installed versions would be removed for successfully updated modules:' -ForegroundColor Yellow
Remove-OldModule -IncludeModule $modulesToProcess.Name -Force:$Force -Verbose:($VerbosePreference -eq 'Continue') -WhatIf
}
return
}
# Update parameters
$updateParams = @{
Verbose = $VerbosePreference -eq 'Continue'
ErrorAction = 'Stop' # Changed to Stop so we can catch errors properly
}
if ($Force)
{
$updateParams.Force = $true
}
if ($SkipPublisherCheck -and $supportsSkipPublisherCheck)
{
$updateParams.SkipPublisherCheck = $true
}
# Update each module individually with ShouldProcess check
$moduleList = if ($modulesToProcess.Count -eq 1) { $modulesToProcess.Name } else { 'selected modules' }
if ($PSCmdlet.ShouldProcess($moduleList, 'Update PowerShell modules'))
{
$updatedCount = 0
$failedCount = 0
$processedCount = 0
$skippedCount = 0
$updatedModuleNames = @()
foreach ($moduleInfo in $modulesToProcess)
{
$processedCount++
$moduleName = $moduleInfo.Name
$currentVersion = $moduleInfo.CurrentVersion
$availableVersion = $moduleInfo.AvailableVersion
# Calculate progress percentage
$percentComplete = if ($modulesToProcess.Count -gt 0)
{
($processedCount / $modulesToProcess.Count) * 100
}
else
{
0
}
Write-Progress -Activity 'Updating PowerShell modules' -Status "Processing $moduleName" -PercentComplete $percentComplete
# Interactive mode: prompt user for each module
if ($Interactive)
{
Write-Host ''
Write-Host "Module: $moduleName" -ForegroundColor Cyan
Write-Host " Current version: $currentVersion" -ForegroundColor Gray
Write-Host " Available version: $availableVersion" -ForegroundColor Gray
$response = Read-Host 'Do you want to update this module? (y/N/a=all/q=quit)'
switch -Regex ($response)
{
'^[Aa]([Ll][Ll])?$'
{
Write-Host 'Updating all remaining modules...' -ForegroundColor Green
$Interactive = $false # Disable interactive mode for remaining modules
break
}
'^[Qq]([Uu][Ii][Tt])?$'
{
Write-Host 'Update process cancelled by user.' -ForegroundColor Yellow
return
}
'^[Yy]([Ee][Ss])?$'
{
# Continue with update
break
}
default
{
Write-Host "Skipping $moduleName" -ForegroundColor Yellow
$skippedCount++
continue
}
}
}
Write-Host "Updating module: $moduleName ($currentVersion -> $availableVersion)" -ForegroundColor Cyan
try
{
$moduleUpdateParams = $updateParams.Clone()
$moduleUpdateParams.Name = $moduleName
Update-Module @moduleUpdateParams
$updatedCount++
$updatedModuleNames += $moduleName
Write-Verbose "Successfully updated $moduleName"
}
catch [Microsoft.PowerShell.Commands.WriteErrorException]
{
$errorMessage = $_.Exception.Message
# Check for specific error conditions
if ($errorMessage -like '*No match was found*')
{
Write-Warning "Module $moduleName not found in repository - skipping"
$skippedCount++
}
elseif ($errorMessage -like '*newer version*' -or $errorMessage -like '*already up to date*')
{
Write-Host " Module $moduleName is already up to date" -ForegroundColor Green
$skippedCount++
}
elseif ($UseElevation -and $script:IsWindowsPlatform -and $errorMessage -like '*Administrator rights are required*')
{
try
{
Write-Host ' Retrying with elevated privileges...' -ForegroundColor Yellow
# Create the script block with embedded variables to avoid parameter passing issues
$elevatedScriptBlock = [ScriptBlock]::Create(@"
`$elevatedUpdateParams = @{
Name = '$moduleName'
ErrorAction = 'Stop'
}
if ('$($Force.IsPresent)' -eq 'True') { `$elevatedUpdateParams.Force = `$true }
if ('$($VerbosePreference -eq 'Continue')' -eq 'True') { `$elevatedUpdateParams.Verbose = `$true }
# Only add SkipPublisherCheck if supported
if ('$($SkipPublisherCheck.IsPresent)' -eq 'True') {
`$psGetModule = Get-Module PowerShellGet -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
if (`$psGetModule -and `$psGetModule.Version -ge [Version]'2.0.0') {
`$elevatedUpdateParams.SkipPublisherCheck = `$true
}
}
Update-Module @elevatedUpdateParams
"@) # End of here-string for elevated script block
# Use Invoke-ElevatedCommand to update the module
Invoke-ElevatedCommand -Scriptblock $elevatedScriptBlock
$updatedCount++
$updatedModuleNames += $moduleName
Write-Host " Successfully updated $moduleName with elevation" -ForegroundColor Green
Write-Verbose "Successfully updated $moduleName with elevation"
}
catch
{
Write-Warning "Failed to update $moduleName even with elevation: $($_.Exception.Message)"
$failedCount++
}
}
else
{
Write-Warning "Failed to update ${moduleName}: $errorMessage"
$failedCount++
}
}
catch [System.InvalidOperationException]
{
$errorMessage = $_.Exception.Message
if ($errorMessage -like '*No match was found*')
{
Write-Warning "Module $moduleName not found in repository - skipping"
$skippedCount++
}
elseif ($errorMessage -like '*newer version*')
{
Write-Host " Module $moduleName is already up to date" -ForegroundColor Green
$skippedCount++
}
elseif ($UseElevation -and $script:IsWindowsPlatform -and $errorMessage -like '*Administrator rights are required*')
{
try
{
Write-Host ' Retrying with elevated privileges...' -ForegroundColor Yellow
# Create the script block with embedded variables to avoid parameter passing issues
$elevatedScriptBlock = [ScriptBlock]::Create(@"
`$elevatedUpdateParams = @{
Name = '$moduleName'
ErrorAction = 'Stop'
}
if ('$($Force.IsPresent)' -eq 'True') { `$elevatedUpdateParams.Force = `$true }
if ('$($VerbosePreference -eq 'Continue')' -eq 'True') { `$elevatedUpdateParams.Verbose = `$true }
# Only add SkipPublisherCheck if supported
if ('$($SkipPublisherCheck.IsPresent)' -eq 'True') {
`$psGetModule = Get-Module PowerShellGet -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
if (`$psGetModule -and `$psGetModule.Version -ge [Version]'2.0.0') {
`$elevatedUpdateParams.SkipPublisherCheck = `$true
}
}
Update-Module @elevatedUpdateParams
"@) # End of here-string for elevated script block
# Use Invoke-ElevatedCommand to update the module
Invoke-ElevatedCommand -Scriptblock $elevatedScriptBlock
$updatedCount++
$updatedModuleNames += $moduleName
Write-Host " Successfully updated $moduleName with elevation" -ForegroundColor Green
Write-Verbose "Successfully updated $moduleName with elevation"
}
catch
{
Write-Warning "Failed to update $moduleName even with elevation: $($_.Exception.Message)"
$failedCount++
}
}
else
{
Write-Warning "Failed to update ${moduleName}: $errorMessage"
$failedCount++
}
}
catch
{
Write-Warning "Failed to update ${moduleName}: $($_.Exception.Message)"
$failedCount++
}
}
Write-Progress -Activity 'Updating PowerShell modules' -Completed
# Display summary
if ($updatedCount -gt 0)
{
Write-Host "Successfully updated $updatedCount module(s)" -ForegroundColor Green
}
if ($skippedCount -gt 0)
{
Write-Host "$skippedCount module(s) were already up to date or skipped" -ForegroundColor Cyan
}
if ($failedCount -gt 0)
{
Write-Host "$failedCount module(s) failed to update" -ForegroundColor Yellow
if ($UseElevation -eq $false -and $script:IsWindowsPlatform)
{
Write-Host ' Tip: Use -UseElevation parameter to automatically handle privilege elevation' -ForegroundColor Gray
}
if ($SkipPublisherCheck -eq $false)
{
Write-Host ' Tip: Use -SkipPublisherCheck parameter to bypass publisher verification issues' -ForegroundColor Gray
}
}
if ($updatedCount -eq 0 -and $failedCount -eq 0 -and $skippedCount -eq 0)
{
Write-Host 'No modules were processed' -ForegroundColor Yellow
}
if ($RemoveOldVersions -and $updatedModuleNames.Count -gt 0)
{
$updatedModuleNames = @($updatedModuleNames | Select-Object -Unique)
try
{
Write-Host 'Removing old versions for successfully updated modules...' -ForegroundColor Cyan
Remove-OldModule -IncludeModule $updatedModuleNames -Force:$Force -Verbose:($VerbosePreference -eq 'Continue')
}
catch
{
Write-Warning "Failed to remove old module versions after update: $($_.Exception.Message)"
}
}
Write-Host 'Module update process completed' -ForegroundColor Green
}
}
catch [System.InvalidOperationException]
{
Write-Error "PowerShellGet operation failed: $($_.Exception.Message)"
Write-Host 'Try running: Install-Module -Name PowerShellGet -Force -AllowClobber' -ForegroundColor Yellow
}
catch [System.UnauthorizedAccessException]
{
Write-Error "Access denied: $($_.Exception.Message)"
Write-Host 'Try running PowerShell as administrator or with elevated permissions' -ForegroundColor Yellow
}
catch
{
Write-Error "Unexpected error during module update: $($_.Exception.Message)"
Write-Verbose "Error details: $($_.Exception.GetType().FullName)"
throw $_
}
}
end
{
Write-Verbose 'Module update process completed'
}
}