Last active
October 13, 2021 09:05
-
-
Save Splaxi/dba292d41841a60fdb1c4f3acca71f40 to your computer and use it in GitHub Desktop.
Helper function to remove old module versions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Uninstall-ModuleOldVersion { | |
[CmdletBinding()] | |
[OutputType()] | |
param ( | |
[Parameter(Mandatory = $false, Position = 1)] | |
[string] $Module = "*" | |
) | |
#Copy & pasted from the work of Jack (@sharepointjack) - http://sharepointjack.com/2017/powershell-script-to-remove-duplicate-old-modules | |
#Will test all installed modules for multiple versions installed on the machine. | |
#All versions that are below the highest will be uninstalled | |
$modules = Get-InstalledModule -Name $Module -ErrorAction SilentlyContinue | |
if ($null -eq $modules) { | |
Write-Host "Unable to locate any module based on the parameter value: $Module" -ForegroundColor Yellow | |
return | |
} | |
foreach ($mod in $modules) { | |
Write-Host "Checking $($mod.name)" -ForegroundColor Yellow | |
$latestModule = Get-InstalledModule -Name $mod.name | |
$specificModules = Get-InstalledModule -Name $mod.name -AllVersions | |
$numberFound = 0 | |
if($null -eq $specificModules.count) { | |
$numberFound = 1 | |
} else { | |
$numberFound = $specificModules.count | |
} | |
Write-Host "$numberFound version(s) of this module found [ $($mod.name) ] - Latest is: $($latestModule.version)" | |
foreach ($specificModule in $specificModules) { | |
if ($specificModule.version -ne $latestModule.version) { | |
Write-Host "Uninstalling $($specificModule.name) - $($specificModule.version) [latest is $($latestModule.version)]" -ForegroundColor Yellow | |
$specificModule | Uninstall-Module -force | |
Write-Host "Done uninstalling $($specificModule.name) - $($specificModule.version)" | |
Write-Host " --------" | |
} | |
} | |
Write-Host "------------------------" | |
} | |
Write-Host "Done" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment