-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-OldModule.ps1
More file actions
340 lines (284 loc) · 12.6 KB
/
Copy pathRemove-OldModule.ps1
File metadata and controls
340 lines (284 loc) · 12.6 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
function Remove-OldModule
{
<#
.SYNOPSIS
Removes all older versions of installed PowerShell modules.
.DESCRIPTION
This function identifies and removes older versions of PowerShell modules that are installed,
keeping only the latest version of each module. This helps maintain a clean PowerShell environment
and reduces disk space usage. Cross-platform compatible with PowerShell 5.1+ on Windows, macOS, and Linux.
.PARAMETER ExcludeModule
Array of module names to exclude from cleanup. These modules will not have old versions removed.
.PARAMETER IncludeModule
Array of specific module names to clean up. When specified, only these modules
will be considered. Cannot be used together with ExcludeModule.
.PARAMETER WhatIf
Shows what modules would be removed without actually removing them.
.PARAMETER Force
Forces removal without prompting for confirmation on protected modules.
.PARAMETER IncludeSystemModules
Includes system modules in the cleanup process. Use with caution.
.EXAMPLE
PS > Remove-OldModule
Removes all older versions of PowerShell modules, keeping only the latest version of each.
.EXAMPLE
PS > Remove-OldModule -ExcludeModule @('PSReadLine', 'PowerShellGet') -WhatIf
Shows what would be removed while excluding specific modules from cleanup.
.EXAMPLE
PS > Remove-OldModule -IncludeModule @('Pester', 'PSScriptAnalyzer')
Removes old versions only for the specified modules.
.EXAMPLE
PS > Remove-OldModule -Force -Verbose
Forces removal of old module versions with verbose output.
.EXAMPLE
PS > Remove-OldModule -IncludeSystemModules -WhatIf
Shows what would be removed including system modules (use with caution).
.EXAMPLE
PS > Remove-OldModule -ExcludeModule @('Azure*', 'PowerShellGet') -IncludeSystemModules
Removes old versions including system modules but excludes Azure modules and PowerShellGet.
.EXAMPLE
PS > Remove-OldModule -Confirm
Removes old module versions with interactive confirmation for each removal operation.
.EXAMPLE
PS > Remove-OldModule -ExcludeModule @('PSReadLine') -Force -Verbose
Forces removal with verbose output while excluding PSReadLine from cleanup.
.OUTPUTS
[System.Void]
No output is returned, but progress information is displayed.
.NOTES
- Requires PowerShell 5.1 or later with PowerShellGet module
- May require elevated permissions on some systems
- System modules are excluded by default for safety
- Always keeps the newest version of each module
- IncludeModule targets specific modules and overrides the default safety exclusions for those modules
Original concept by Luke Murray (Luke.Geek.NZ)
Enhanced for cross-platform compatibility and error handling
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/ModuleManagement/Remove-OldModule.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/ModuleManagement/Remove-OldModule.ps1
.LINK
https://luke.geek.nz/powershell/remove-old-powershell-modules-versions-using-powershell/
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(SupportsShouldProcess)]
[OutputType([System.Void])]
param(
[Parameter()]
[String[]]$ExcludeModule = @(),
[Parameter()]
[String[]]$IncludeModule = @(),
[Parameter()]
[Switch]$Force,
[Parameter()]
[Switch]$IncludeSystemModules
)
begin
{
Write-Verbose 'Starting old module cleanup process'
$cancelCleanupProcess = $false
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.'
$cancelCleanupProcess = $true
return
}
# System modules that should typically be excluded for safety
$systemModules = @(
'Microsoft.PowerShell.*',
'PowerShellGet',
'PackageManagement',
'PSReadLine'
)
# Build the final exclusion list
$finalExcludeList = $ExcludeModule
if (-not $IncludeSystemModules)
{
$finalExcludeList += $systemModules
Write-Verbose "Excluding system modules: $($systemModules -join ', ')"
}
}
process
{
if ($cancelCleanupProcess)
{
Write-Verbose 'Old module cleanup process cancelled before execution'
return
}
try
{
# Get all installed modules
Write-Host 'Retrieving installed modules...' -ForegroundColor Cyan
$allModules = @(Get-InstalledModule -ErrorAction Stop)
if (-not $allModules -or $allModules.Count -eq 0)
{
Write-Host 'No modules found.' -ForegroundColor Yellow
return
}
if ($IncludeModule.Count -gt 0)
{
$modulesToProcess = foreach ($installedModule in $allModules)
{
foreach ($includePattern in $IncludeModule)
{
if ($installedModule.Name -like $includePattern)
{
$installedModule
break
}
}
}
$notFoundPatterns = foreach ($includePattern in $IncludeModule)
{
if (-not ($allModules | Where-Object { $_.Name -like $includePattern }))
{
$includePattern
}
}
foreach ($missingPattern in $notFoundPatterns)
{
Write-Warning "No installed modules matched IncludeModule pattern '$missingPattern'"
}
}
elseif ($ExcludeModule.Count -gt 0)
{
$modulesToProcess = $allModules | Where-Object { $_.Name -notin $ExcludeModule }
}
else
{
$modulesToProcess = $allModules
}
$modulesToProcess = @($modulesToProcess)
if (-not $modulesToProcess -or $modulesToProcess.Count -eq 0)
{
Write-Host 'No modules found to clean up.' -ForegroundColor Yellow
return
}
Write-Host "Found $($modulesToProcess.Count) installed module(s) to evaluate" -ForegroundColor Green
$processedCount = 0
$removedCount = 0
$identifiedOldVersionCount = 0
foreach ($latestModule in $modulesToProcess)
{
$processedCount++
$moduleName = $latestModule.Name
# IncludeModule explicitly targets the requested modules, even if they are otherwise excluded for safety.
if ($IncludeModule.Count -eq 0)
{
$shouldExclude = $false
foreach ($excludePattern in $finalExcludeList)
{
if ($moduleName -like $excludePattern)
{
$shouldExclude = $true
break
}
}
if ($shouldExclude)
{
Write-Verbose "Skipping excluded module: $moduleName"
continue
}
}
# Calculate progress percentage safely
$percentComplete = if ($modulesToProcess.Count -gt 0)
{
($processedCount / $modulesToProcess.Count) * 100
}
else
{
0
}
Write-Progress -Activity 'Cleaning up old module versions' -Status "Processing $moduleName" -PercentComplete $percentComplete
try
{
# Get all versions of this module
$allVersions = Get-InstalledModule -Name $moduleName -AllVersions -ErrorAction Stop
$oldVersions = $allVersions | Where-Object { $_.Version -ne $latestModule.Version }
if ($oldVersions)
{
$oldVersions = @($oldVersions)
$identifiedOldVersionCount += $oldVersions.Count
$oldVersionList = ($oldVersions | ForEach-Object { $_.Version }) -join ', '
Write-Host "Processing $moduleName [latest: $($latestModule.Version)] - found old versions: $oldVersionList" -ForegroundColor Cyan
foreach ($oldVersion in $oldVersions)
{
if ($PSCmdlet.ShouldProcess("$moduleName version $($oldVersion.Version)", 'Uninstall'))
{
try
{
$uninstallParams = @{
Name = $moduleName
RequiredVersion = $oldVersion.Version
Verbose = $VerbosePreference -eq 'Continue'
ErrorAction = 'Stop'
}
if ($Force)
{
$uninstallParams.Force = $true
}
Uninstall-Module @uninstallParams
$removedCount++
Write-Verbose "Successfully removed $moduleName version $($oldVersion.Version)"
}
catch [System.InvalidOperationException]
{
Write-Warning "Could not remove $moduleName version $($oldVersion.Version): Module may be in use or protected"
}
catch [System.UnauthorizedAccessException]
{
Write-Warning "Access denied removing $moduleName version $($oldVersion.Version): Try running with elevated permissions"
}
catch
{
Write-Warning "Failed to remove $moduleName version $($oldVersion.Version): $($_.Exception.Message)"
}
}
}
}
else
{
Write-Verbose "No old versions found for $moduleName"
}
}
catch
{
Write-Warning "Error processing module $moduleName`: $($_.Exception.Message)"
continue
}
}
Write-Progress -Activity 'Cleaning up old module versions' -Completed
if ($WhatIfPreference -and $identifiedOldVersionCount -gt 0)
{
Write-Host "WhatIf: Would remove $identifiedOldVersionCount old module version(s)" -ForegroundColor Yellow
}
elseif ($removedCount -gt 0)
{
Write-Host "Successfully removed $removedCount old module version(s)" -ForegroundColor Green
}
elseif ($identifiedOldVersionCount -gt 0)
{
Write-Host "Identified $identifiedOldVersionCount old module version(s), but none were removed" -ForegroundColor Yellow
}
else
{
Write-Host 'No old module versions found to remove' -ForegroundColor Yellow
}
}
catch [System.Management.Automation.CommandNotFoundException]
{
Write-Error 'PowerShellGet module not found. Please install it: Install-Module -Name PowerShellGet -Force'
}
catch
{
Write-Error "Unexpected error during module cleanup: $($_.Exception.Message)"
Write-Verbose "Error details: $($_.Exception.GetType().FullName)"
throw $_
}
}
end
{
Write-Verbose 'Old module cleanup process completed'
}
}