Uninstall-OldModuleVersion.psm1
function Uninstall-OldModuleVersion { <# .SYNOPSIS Uninstalls older versions of installed PowerShell modules. .DESCRIPTION This function iterates through all installed PowerShell modules and uninstalls versions that are older than the current installed version. .EXAMPLE Uninstall-OldModuleVersion .NOTES This function requires PowerShellGet to be installed. #> # Checks if current session is elevated $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (!($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) { Write-Warning "Must be run as Administrator" return } # Get all installed modules $installedModule = Get-InstalledModule # Iterate over each installed module foreach ($module in $installedModule) { # Get the current version of the module $currentVersion = $module.Version # Display the module name and current version Write-Host "Checking " -NoNewline Write-Host $module.Name -ForegroundColor Cyan -NoNewline Write-Host " version " -NoNewline Write-Host $currentVersion -ForegroundColor Cyan -NoNewline # Get all installed versions of the module that are older than the current version $removeable = Get-InstalledModule -Name $module.Name -AllVersions | Where-Object -Property "Version" -lt -Value $currentVersion # Check if there are any older versions to uninstall if ($removeable) { # If there are older versions, display the version being uninstalled and uninstall it Write-Host " [uninstalling]" -ForegroundColor Yellow $removeable | Uninstall-Module -Confirm -Verbose } else { # If no older versions, indicate that the module passed the check Write-Host " [passed]" -ForegroundColor Green } } } |