Public/Uninstall-pseModule.ps1

Function Uninstall-pseModule {
    <#
    .SYNOPSIS
        Uninstalls one or more specified PowerShell modules.
 
    .DESCRIPTION
        The Uninstall-pseModule function removes all installed PowerShell modules of the name specified from your system.
        For example, if you specify 'AzureAD', all installed versions of the 'AzureAD' module will be uninstalled.
 
    .PARAMETER moduleName
         One or more PowerShell module names to uninstall. Can be provided as:
           * A single string
           * An array of strings
           * Pipeline input
 
    .EXAMPLE
        Uninstall-pseModule -moduleName AzureAD
 
        Uninstalls the 'AzureAD' module.
 
    .EXAMPLE
        Uninstall-pseModule -moduleName "DHCPServer", "RemoteDesktop"
 
        Uninstalls multiple modules in a single command.
 
    .NOTES
        Author : owen.heaume
        Version: 1.0.0 - Initial release
    #>


    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$ModuleName
    )

    Process {
        foreach ($module in $ModuleName) {
            Write-Host "Attempting to uninstall module '$module'" -ForegroundColor DarkCyan

            # Check if module is installed
            $moduleInfo = Get-Module -Name $module -ListAvailable
            if (!$moduleInfo) {
                Write-Warning "Module '$module' is not installed.`n"
                continue
            }

            if ($PSCmdlet.ShouldProcess("'$module'", "Uninstall-Module")) {
                try {
                    Uninstall-Module -Name $module -AllVersions -Force -ErrorAction Stop
                    Write-Host "Module '$module' has been uninstalled`n" -ForegroundColor DarkGreen
                } catch {
                    Write-Error "An unexpected error occurred: $_"
                }
            }
        }
    }
}