Last active
January 22, 2024 16:14
-
-
Save SvenAelterman/7ac014fe2751a953dd80b03d92dbb19f to your computer and use it in GitHub Desktop.
Uninstall-OutdatedModules.ps1
This file contains hidden or 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
[CmdletBinding(SupportsShouldProcess = $True)] | |
Param( | |
[Parameter(Mandatory, Position = 1)] | |
[string]$ModuleName, | |
[Parameter(Position = 2)] | |
[bool]$DeleteChildModules = $true | |
) | |
$Latest = Get-InstalledModule $ModuleName -ErrorAction Ignore; | |
# If this module is installed at all | |
if ($Latest) { | |
Write-Verbose "Latest installed version of '$ModuleName' is $($Latest.Version)" | |
# Create an array of module names to check | |
[array]$AllModules = @($Latest) | |
if ($DeleteChildModules) { | |
# Add a wildcard at the end | |
$WildcardModuleName = "$ModuleName$(if ($DeleteChildModules) { '.*' })" | |
# Retrieve all modules that start with the module name, add them to the array | |
$AllModules += Get-InstalledModule $WildcardModuleName -ErrorAction SilentlyContinue | |
Write-Verbose "Found $($AllModules.Length - 1) child modules to check" | |
} | |
# Loop through all modules (parent + children) | |
foreach ($CurrentModule in $AllModules) { | |
$Latest = Get-InstalledModule $CurrentModule.Name | |
$ModulesToRemove = Get-InstalledModule $CurrentModule.Name -AllVersions | ` | |
Where-Object { $_.Version -ne $Latest.Version } | |
Write-Verbose "Found $($ModulesToRemove.Length) old versions of '$($CurrentModule.Name)'" | |
foreach ($ModuleToRemove in $ModulesToRemove) { | |
Write-Host "Uninstalling version '$($ModuleToRemove.Version)' of '$($ModuleToRemove.Name)'" | |
Uninstall-Module -InputObject $ModuleToRemove -WhatIf:$WhatIfPreference -Force | |
} | |
} | |
} | |
else { | |
Write-Warning "No installed version of $ModuleName found" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Significant update that's better at handling parent/child modules.
Usage example: