Skip to content

Instantly share code, notes, and snippets.

@SvenAelterman
Last active January 22, 2024 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SvenAelterman/7ac014fe2751a953dd80b03d92dbb19f to your computer and use it in GitHub Desktop.
Save SvenAelterman/7ac014fe2751a953dd80b03d92dbb19f to your computer and use it in GitHub Desktop.
Uninstall-OutdatedModules.ps1
[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"
}
@SvenAelterman
Copy link
Author

Significant update that's better at handling parent/child modules.

Usage example:

.\Uninstall-OutdatedModules.ps1 Az -Verbose -WhatIf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment