Cleaning Up PowerShell Modules (Part 3)

by Jul 5, 2022

In part 1 and 2 we looked at removing PowerShell modules altogether. In this last part we’ll look at PowerShell module versions you may no longer need.

Whenever a PowerShell module is updated to a new version, the new version is simply saved side-by-side with all older versions. That’s smart because this design enables you to update modules even if they are currently in use.

Yet this design also results in a growing pile of garbage. Unless there is no need for you to explicitly go back to an older version of a module, you typically only need the latest version of a module.

That’s why the script below identifies all modules that are available in more than one version and then lets the user decide which of these should be cleaned:

# script may require Administrator privileges if you want to remove
# module versions installed in "AllUsers" scope

# find ALL modules with more than one version and/or location:
$multiversion = Get-Module -ListAvailable | 
  Group-Object -Property Name | 
  Sort-Object -Property Name |
  Where-Object Count -gt 1

# ask user WHICH of these modules to clean?
$clean = $multiversion | 
    Select-Object -Property @{N='Versions';E={$_.Count}}, @{N='ModuleName';E={$_.Name}} |
    Out-GridView -Title 'Select module(s) to clean' -PassThru

# get the todo list with the modules the user wants to clean:
$todo = $multiversion | Where-Object Name -in $clean.ModuleName

$todo |
  ForEach-Object {
    $module = $_.Name
    # list all versions of a given module and let the user decide which versions
    # to keep and which to remove:
    $_.Group | 
        Select-Object -Property Version, ModuleBase, ReleaseNotes |
        Sort-Object -Property Version |
        Out-GridView -Title "Module $module : Select all versions that you want to remove" -PassThru |
        Select-Object -ExpandProperty ModuleBase |
        # do a last confirmation dialog before permanently deleting the subversions:
        Out-GridView -Title 'Do you really want to permanently delete these folders? CTRL+A and OK to confirm' -PassThru  |
        Remove-Item -Recurse -Force


Once the user selected one or more modules to clean, the script processes one module at a time and lists all versions of it. The user can then select the versions to delete.

Note that you may need Administrator privileges to remove module versions installed in “AllUsers” scope.

Twitter This Tip! ReTweet this Tip!