cleanup.ps1

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
    $module = "dbatools"
)

$isElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

# Which process should we be looking for?
if ($psedition -eq 'Core') {
    $process = "pwsh"
} else {
    $process = "powershell"
}
$ise = Get-Process powershell_ise -ErrorAction SilentlyContinue
if ($ise) {
    return "PowerShell ISE found in use. Please close this program before using this script."
}

$installedVersion = Get-InstalledModule $module -AllVersions | Select-Object Version,InstalledLocation
Write-Output "The currently installed version(s) of $module is/are: "
$installedVersion.Version

$results =
foreach ($v in $installedVersion) {
    if ($v.InstalledLocation -match "C:\\Users") {
        Add-Member -Force -InputObject $v -MemberType NoteProperty -Name IsUserScope -value $true
    } else {
        if (-not $isElevated) {
            Write-Output "$module version $v.Version cannot be removed without elevated session."
        }
        Add-Member -Force -InputObject $v -MemberType NoteProperty -Name IsUserScope -value $false
    }
    $v
}

$newestVersion = Find-Module $module | Select-Object Version
Write-Output "`nThe latest version of $module in the PSGallery is: $($newestVersion.Version)"
if ($installedVersion.Count -gt 1) {
    $olderVersions = $installedVersion | Where-Object Version -lt $newestVersion.Version
}

if ( ($olderVersions.Count -gt 0) -and $newestVersion.Version -in $installedVersion.Version ) {
    Write-Output "Latest version of $module found on $env:COMPUTERNAME."
    Write-Output "Older versions of $module also found. These will be uninstalled now."
    if ($isElevated) {
        $processes = Get-Process $process -IncludeUserName -ErrorAction SilentlyContinue | Where-Object Id -NE $pid
    } else {
        $processes = Get-Process $process -ErrorAction SilentlyContinue | Where-Object Id -NE $PID
    }
    if ($processes.Count -gt 0) {
        if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Killing $($processes.Count) processes of powershell running")) {
            Write-Output "Death to the following process(es): $(($processes.Id) -join ",")"
            $processes | Stop-Process -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                Write-Warning "Not able to kill following processes: $((Get-Process $process | Where-Object Id -NE $pid).Id -join ",")"
            }
        }
    }
    if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Removing old versions of $module.")) {
        foreach ($v in $olderVersions.Version) {
            Uninstall-Module $module -RequiredVersion $v -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                if ($dangit.Exception -like "*Administrator rights*") {
                    Write-Warning "Elevated session is required to uninstall $module version: $v"
                } else {
                    Write-Warning "Unable to remove $module version [$v] due to: `n`t$($dangit.Exception)"
                }
            }
        }
    }
    Write-Output "The End"
} elseif ( ($olderVersions.Count -gt 0) -and $newestVersion.Version -notin $installedVersion.Version ) {
    Write-Output "Update of $module is available"
    Write-Output "Older versions of $module found. These will be uninstalled now."
    if ($isElevated) {
        $processes = Get-Process $process -ErrorAction SilentlyContinue -IncludeUserName | Where-Object Id -NE $pid
    } else {
        $processes = Get-Process $process -ErrorAction SilentlyContinue | Where-Object Id -NE $PID
    }
    if ($processes.Count -gt 0) {
        if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Killing $($processes.Count) processes of powershell running")) {
            Write-Output "Death to the following process(es): $(($processes.Id) -join ",")"
            $processes | Stop-Process -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                Write-Warning "Not able to kill following processes: $((Get-Process $process | Where-Object Id -NE $pid).Id -join ",")"
            }
        }
    }
    if ($Pscmdlet.ShouldProcess("$env:COMPUTERNAME", "Removing old versions of $module.")) {
        foreach ($v in $olderVersions.Version) {
            Uninstall-Module $module -RequiredVersion $v -ErrorVariable dangit -ErrorAction SilentlyContinue -Force
            if ($dangit) {
                if ($dangit.Exception -like "*Administrator rights*") {
                    Write-Warning "Elevated session is required to uninstall $module version: $v"
                } else {
                    Write-Warning "Unable to remove $module version [$v] due to: `n`t$($dangit.Exception)"
                }
            }
        }
    }
    Write-Output "Continuing to install latest release of $module"
    Install-Module $module -Force
    Write-Output "The End"
} else {
    Write-Output "No update/actions required."
}