Skip to content

Module Cleanup

John G Hohengarten edited this page Apr 22, 2019 · 16 revisions

Author:

wsuhoey (John G Hohengarten)

Contributors:

ben.thul (Ben Thul) for multiple old version logic. Thanks!

Purpose:

Script for cleaning up all older versions of the module and updating your machine to the latest release.

Caveats/Known Issues:

  • Does NOT consider or check if dbachecks module is installed, which might have a specific dependency on a required or minimum version of dbatools to be installed.

Script:

$module = "dbatools"

[array]$currentVersion = Get-Module $module -ListAvailable | Select-Object -ExpandProperty Version
$newVersion = Find-Module $module | Select-Object -ExpandProperty Version

Write-Output "The currently installed version(s) of $module is $currentVersion"
Write-Output "The latest version of $module in the PSGallery is $newVersion"

<#
    # check what latest version is in PSGallery, full results
    Find-Module $module
#>
<#
    # check what latest version is in PSGallery
    Find-Module $module | Select-Object Version, PublishedDate
#>

if ( $currentVersion -lt $newVersion ) {
    Write-Output "New version of $module in PSGallery detected...`nWARNING: Finding and killing all other instances of powershell.exe and powershell_ise.exe to prevent uninstall issues later due to being in-use. (This could impact Agent Jobs if run on a server)"

    Get-Process PowerShell* | Where-Object Id -NE $PID | ForEach-Object { Stop-Process -Confirm $_ }
    Write-Output "Now updating $module to $newVersion..."
    Get-Module $module | Remove-Module
    Update-Module $module

    foreach ($oldversion in $currentversion) {
        Write-Output "Uninstalling old version $module $oldversion"
        Uninstall-Module $module -RequiredVersion $oldversion
    }

    Write-Output "Update completed!"
    Write-Output "Recommended to exit this powershell.exe or powershell_ise.exe"
} else {
    Write-Output "No update needed."
}