Public/Uninstall-SpecPowerShellModule.ps1

function Uninstall-SpecPowerShellModule {
    <#
    .SYNOPSIS
    This function uninstalls a specified PowerShell module and all its installed versions.
 
    .DESCRIPTION
    The Uninstall-SpecPowerShellModule function uninstalls the specified PowerShell module and all its installed versions. It first checks for all installed versions of the module and then uninstalls each version one by one.
 
    .PARAMETER ModuleName
    The name of the PowerShell module to uninstall.
 
    .EXAMPLE
    Uninstall-SpecPowerShellModule -ModuleName "ExampleModule"
 
    Description:
    This example uninstalls all versions of the PowerShell module named "ExampleModule".
 
    .EXAMPLE
    "Module", "Module2" | Uninstall-SpecPowerShellModule
 
    Description:
    This example uninstalls all versions of the PowerShell module named "Module1" and "Module2" using the pipeline.
 
    .NOTES
    Author : owen.heaume
    Version : 1.0
#>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$ModuleName
    )

    Begin { }

    Process {
        foreach ($module in $ModuleName) {
            try {
                $moduleVersions = @()

                # Get all installed versions of the module
                write-host "`nGetting installed versions of module: [$ModuleName]" -ForegroundColor DarkCyan
                $moduleVersions += Get-Module -Name $ModuleName -ListAvailable | Select-Object Version | Sort-Object Version -Descending -ea Stop

                if ($moduleVersions.Count -eq 0) {
                    Write-Host "No installed versions of module: [$ModuleName]" -ForegroundColor DarkGray
                } else {
                    Write-Host "Found $($moduleVersions.Count) installed versions of module: [$ModuleName]" -ForegroundColor DarkGray
                }
            } catch {
                Write-Host "Module not found: [$ModuleName]" -ForegroundColor darkYellow
            }

            # Uninstall each version of the module
            foreach ($moduleVersion in $moduleVersions) {
                try {
                    Write-Host "Uninstalling module: [$ModuleName] version [$($moduleVersion.Version)]" -ForegroundColor Darkgray
                    Uninstall-Module -Name $ModuleName -RequiredVersion $moduleVersion.Version -Force -ea Stop
                    Write-Host "Uninstalled module: [$ModuleName] version [$($moduleVersion.Version)]" -ForegroundColor DarkGreen
                } catch {
                    Write-Host "Error uninstalling module: [$ModuleName] version [$($moduleVersion.Version)]" -ForegroundColor darkYellow
                }
            }
        }
    }

    End { }

}