-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-PsResourceWithClean.ps1
More file actions
49 lines (36 loc) · 1.73 KB
/
Update-PsResourceWithClean.ps1
File metadata and controls
49 lines (36 loc) · 1.73 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
# update a module, then cleanup old versions of a module installed from PSGallery
# disable progress bar
$startProg = $global:ProgressPreference
$global:ProgressPreference = "SilentlyContinue"
# all modules from the PSGallery
$allMods = Get-InstalledPSResource | Where-Object Repository -eq "PSGallery"
# group the modules by name and filter out modules with more than one entry
[array]$modGroups = $allMods | Group-Object -Property Name
# perform the cleanup
foreach ($m in $modGroups) {
# get the mod name
$modName = $m.Name
# update the module
Write-Host "Updating $modName."
Update-PSResource -Name $modName -Force -Confirm:$false
# get an update of all versions of the module
$allVersions = Get-PSResource -Name $modName
if ($allVersions.Count -gt 1) {
Write-Host "Cleaning up old versions of $modName."
# get the newest version of the module
$newestVersion = $allVersions | Sort-Object -Property Version -Descending -Top 1 | ForEach-Object Version
# older versions
[array]$oldVersions = $allMods | Where-Object { $_.Name -eq $modName -and $_.Version -ne $newestVersion }
# remove old versions
$oldVersions | ForEach-Object { Uninstall-PSResource -Name $modName -Version $_.Version -Confirm:$false }
# there should only be one version of the module left
if ( (Get-InstalledPSResource $modName).Count -gt 1 ) {
Write-Host -ForegroundColor Red "Failed to cleanup $modName."
} else {
Write-Host -ForegroundColor Green "$modName was successfully cleaned up."
}
}
Remove-Variable modName, allVersions, newestVersion, oldVersions -EA SilentlyContinue
}
# reset progress
$global:ProgressPreference = $startProg