-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathpsmodules-del.ps1
267 lines (227 loc) · 12.1 KB
/
psmodules-del.ps1
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
<# CIAOPS
Script provided as is. Use at own risk. No guarantees or warranty provided.
Source - https://github.com/directorcia/Office365/blob/master/psmodules-del.ps1
Description - Remove old versions of PowerShell modules
Prerequisites - PowerShell 5.1 or later
Get-OldPSModules -ModuleNames "Microsoft.Graph", "Microsoft.Online.SharePoint.PowerShell"
More scripts available by joining http://www.ciaopspatron.com
#>
function Remove-OldPSModules {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string[]]$ModuleNames = @(),
[Parameter(Mandatory=$false)]
[switch]$ConfirmUninstall,
[Parameter(Mandatory=$false)]
[switch]$WhatIf,
[Parameter(Mandatory=$false)]
[switch]$SummaryOnly
)
# Create summary tracking variables
$script:TotalModulesProcessed = 0
$script:TotalVersionsRemoved = 0
$script:TotalVersionsSkipped = 0
$script:TotalErrors = 0
$script:ModuleSummary = @()
# Display script header
Write-Host "`n========================================================" -ForegroundColor Cyan
Write-Host " PowerShell Module Version Cleanup Tool" -ForegroundColor Cyan
Write-Host " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan
Write-Host "========================================================`n" -ForegroundColor Cyan
# If WhatIf is specified, notify the user
if ($WhatIf) {
Write-Host "RUNNING IN SIMULATION MODE (WhatIf). No modules will be removed." -ForegroundColor Yellow
Write-Host "Use without -WhatIf to perform actual removal.`n" -ForegroundColor Yellow
}
# If no modules specified, get all installed module names
if (-not $ModuleNames) {
Write-Host "No specific modules specified. Scanning all installed modules..." -ForegroundColor Cyan
$AllModules = Get-InstalledModule -ErrorAction SilentlyContinue
if ($null -eq $AllModules) {
Write-Host "No modules found installed via PowerShellGet." -ForegroundColor Red
return
}
$ModuleNames = $AllModules | Select-Object -ExpandProperty Name | Get-Unique
Write-Host "Found $($ModuleNames.Count) installed modules:" -ForegroundColor Green
# List all modules one per line
Write-Host "`nINSTALLED MODULES:" -ForegroundColor Cyan
foreach ($module in $ModuleNames) {
Write-Host " - $module" -ForegroundColor Gray
}
Write-Host ""
}
else {
Write-Host "Processing specified modules:" -ForegroundColor Cyan
foreach ($module in $ModuleNames) {
Write-Host " - $module" -ForegroundColor Gray
}
Write-Host ""
}
# Create a progress bar for module processing
$progressParams = @{
Activity = "Processing PowerShell Modules"
Status = "Starting module cleanup"
PercentComplete = 0
}
Write-Progress @progressParams
$moduleCounter = 0
foreach ($ModuleName in $ModuleNames) {
$moduleCounter++
$progressParams.PercentComplete = ($moduleCounter / $ModuleNames.Count) * 100
$progressParams.Status = "Processing module $moduleCounter of $($ModuleNames.Count): $ModuleName"
Write-Progress @progressParams
$moduleSummary = [PSCustomObject]@{
Name = $ModuleName
LatestVersion = "N/A"
RemovedVersions = 0
SkippedVersions = 0
Error = $null
}
try {
if (-not $SummaryOnly) {
Write-Host "`n== Processing module: $ModuleName ==" -ForegroundColor Magenta
}
# Get all installed versions of the module, ordered by version descending
$InstalledModules = Get-InstalledModule -Name $ModuleName -AllVersions -ErrorAction Stop |
Sort-Object Version -Descending
# If more than one version exists
if ($InstalledModules.Count -gt 1) {
# The first module in the sorted list is the latest version
$LatestVersion = $InstalledModules[0]
$moduleSummary.LatestVersion = $LatestVersion.Version
if (-not $SummaryOnly) {
Write-Host "Found $($InstalledModules.Count) versions of '$ModuleName':" -ForegroundColor White
Write-Host " - Latest: v$($LatestVersion.Version) (will be kept)" -ForegroundColor Green
Write-Host " - Older versions:" -ForegroundColor Yellow
for ($i = 1; $i -lt $InstalledModules.Count; $i++) {
Write-Host " $(if($WhatIf){"[SIMULATION] "})[v$($InstalledModules[$i].Version)] Published: $($InstalledModules[$i].PublishedDate)" -ForegroundColor Yellow
}
}
# Iterate through the older versions (starting from the second element)
for ($i = 1; $i -lt $InstalledModules.Count; $i++) {
$OlderVersion = $InstalledModules[$i]
if ($ConfirmUninstall) {
if (-not $SummaryOnly) {
Write-Host "`nOlder version: v$($OlderVersion.Version)" -NoNewline
Write-Host " [Published: $($OlderVersion.PublishedDate)]" -ForegroundColor Gray
}
$ConfirmationResult = Read-Host "Confirm removal? (Y/N)"
if ($ConfirmationResult -ceq "Y") {
Uninstall-Module -Name $ModuleName -RequiredVersion $OlderVersion.Version -Force -WhatIf:$WhatIf
if (-not $WhatIf) {
$script:TotalVersionsRemoved++
$moduleSummary.RemovedVersions++
if (-not $SummaryOnly) {
Write-Host " ✓ Removed v$($OlderVersion.Version)" -ForegroundColor Green
}
}
else {
if (-not $SummaryOnly) {
Write-Host " [SIMULATION] Would remove v$($OlderVersion.Version)" -ForegroundColor Cyan
}
}
}
else {
$script:TotalVersionsSkipped++
$moduleSummary.SkippedVersions++
if (-not $SummaryOnly) {
Write-Host " ⊘ Skipped removal of v$($OlderVersion.Version)" -ForegroundColor Yellow
}
}
}
else {
# Automatic removal without confirmation
Uninstall-Module -Name $ModuleName -RequiredVersion $OlderVersion.Version -Force -WhatIf:$WhatIf
if (-not $WhatIf) {
$script:TotalVersionsRemoved++
$moduleSummary.RemovedVersions++
if (-not $SummaryOnly) {
Write-Host " ✓ Removed v$($OlderVersion.Version)" -ForegroundColor Green
}
}
else {
if (-not $SummaryOnly) {
Write-Host " [SIMULATION] Would remove v$($OlderVersion.Version)" -ForegroundColor Cyan
}
}
}
}
if (-not $SummaryOnly) {
Write-Host "`n✓ Kept latest version of $ModuleName : v$($LatestVersion.Version)" -ForegroundColor Green
}
$script:TotalModulesProcessed++
}
elseif ($InstalledModules.Count -eq 1) {
$moduleSummary.LatestVersion = $InstalledModules[0].Version
if (-not $SummaryOnly) {
Write-Host "Only one version found for '$ModuleName': v$($InstalledModules[0].Version)" -ForegroundColor Yellow
Write-Host "No cleanup needed." -ForegroundColor Yellow
}
$script:TotalModulesProcessed++
}
else {
if (-not $SummaryOnly) {
Write-Host "No versions of '$ModuleName' found installed via PowerShellGet." -ForegroundColor Yellow
}
}
}
catch {
$script:TotalErrors++
$errorMessage = $_.Exception.Message
$moduleSummary.Error = $errorMessage
if (-not $SummaryOnly) {
Write-Host "❌ Error processing module '$ModuleName': $errorMessage" -ForegroundColor Red
}
}
# Add to summary collection
$script:ModuleSummary += $moduleSummary
}
# Complete the progress bar
Write-Progress -Activity "Processing PowerShell Modules" -Completed
# Display summary report
Write-Host "`n========================================================" -ForegroundColor Cyan
Write-Host " SUMMARY REPORT" -ForegroundColor Cyan
Write-Host "========================================================" -ForegroundColor Cyan
Write-Host "Total modules processed: $script:TotalModulesProcessed" -ForegroundColor White
Write-Host "Total versions removed: $(if($WhatIf){"[SIMULATION] "})$script:TotalVersionsRemoved" -ForegroundColor $(if($script:TotalVersionsRemoved -gt 0){"Green"}else{"White"})
Write-Host "Total versions skipped: $script:TotalVersionsSkipped" -ForegroundColor $(if($script:TotalVersionsSkipped -gt 0){"Yellow"}else{"White"})
Write-Host "Total errors encountered: $script:TotalErrors" -ForegroundColor $(if($script:TotalErrors -gt 0){"Red"}else{"White"})
if ($script:ModuleSummary.Count -gt 0) {
Write-Host "`nDETAILS BY MODULE:" -ForegroundColor Cyan
foreach ($summary in $script:ModuleSummary) {
$statusColor = if ($summary.Error) { "Red" } elseif ($summary.RemovedVersions -gt 0) { "Green" } else { "White" }
Write-Host " - $($summary.Name): " -NoNewline
Write-Host "Latest v$($summary.LatestVersion)" -ForegroundColor Green -NoNewline
if ($summary.RemovedVersions -gt 0) {
if ($WhatIf) {
Write-Host ", Would remove $($summary.RemovedVersions) older version(s)" -ForegroundColor Cyan -NoNewline
} else {
Write-Host ", Removed $($summary.RemovedVersions) older version(s)" -ForegroundColor Green -NoNewline
}
}
if ($summary.SkippedVersions -gt 0) {
Write-Host ", Skipped $($summary.SkippedVersions) version(s)" -ForegroundColor Yellow -NoNewline
}
if ($summary.Error) {
Write-Host ", ERROR: $($summary.Error)" -ForegroundColor Red -NoNewline
}
Write-Host ""
}
}
Write-Host "`nCleanup operation completed at $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan
if ($WhatIf) {
Write-Host "NOTE: This was a simulation run. Use without -WhatIf to perform actual removal." -ForegroundColor Yellow
}
Write-Host "========================================================`n" -ForegroundColor Cyan
}
Clear-Host
# Example usage:
# Remove-OldPSModules # Process all modules without confirmation
# Remove-OldPSModules -SummaryOnly # Only show summary info, minimize verbose output
# Remove-OldPSModules -ModuleNames "Microsoft.Graph", "Az" # Process specific modules
# Remove-OldPSModules -ConfirmUninstall # Ask before each removal
# Remove-OldPSModules -WhatIf # Simulation mode, no actual changes
# Remove-OldPSModules -ModuleNames "Az" -ConfirmUninstall -WhatIf # Combine parameters as needed
# Run the script with your chosen parameters
Remove-OldPSModules -ConfirmUninstall