PowerShell Modules Maintenance - Updated

Page content

Introduction

Almost a year ago, I wrote an article on this topic. Since it appeared in my search results for the same question again (that’s why I am blogging - not enough, to be honest), I took the opportunity to review the article and post an updated version with an improved script.

It’ll still update installed modules and remove older version in the C:\Users\<username>\Documents\PowerShell\Modules folder, but in a more userfriendly way :-)

PowerShell Script

By trusting the registry it is not necessary to confirm module updates every time. The script will iterate all installed modules, check each for updates, install them and remove older versions.

Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
$installedModules = Get-InstalledModule
$i = 0

foreach ($module in $installedModules) {
    $i++
    Write-Host -NoNewline "Processing module $i of $($installedModules.Count): $($module.Name) (Version $($module.Version))"
    Update-Module -Name $module.Name
    $versionsToRemove = Get-InstalledModule -Name $module.Name -AllVersions | Where-Object { $_.Version -ne $module.Version }
    if ($versionsToRemove) {
        Write-Host -NoNewline " Removing $($versionsToRemove.Version -join ', ')"
        $versionsToRemove | ForEach-Object { Uninstall-Module -Name $_.Name -RequiredVersion $_.Version -Force }
    }
    Write-Host " - Done."
}

You can download the script here.

It’ll take a while to run the cleanup script, depending on the amount of installed modules and version.

Processing module 1 of 124: ALZ (Version 6.0.5) - Done.
Processing module 2 of 124: Az (Version 15.2.0) - Done.
...
Processing module 111 of 124: Microsoft.Graph.Reports (Version 2.28.0) Removing versions: 2.34.0 - Done.
Processing module 112 of 124: Microsoft.Graph.SchemaExtensions (Version 2.28.0) Removing versions: 2.34.0 - Done.
Processing module 113 of 124: Microsoft.Graph.Search (Version 2.28.0) Removing versions: 2.34.0 - Done.
Processing module 114 of 124: Microsoft.Graph.Security (Version 2.28.0) Removing versions: 2.34.0

Summary

Updating PowerShell modules and removing old version is still a manual task, but with a script the tasks can be automated.