Private/Helper/Uninstall-IntegrisModuleDependency.ps1

<#
Copyright © 2024 Integris. For internal company use only. All rights reserved.
#>


FUNCTION Uninstall-IntegrisModuleDependency {
    <#
    .SYNOPSIS
    Uninstalls a specified PowerShell module.
 
    .DESCRIPTION
    This function attempts to uninstall a specified PowerShell module using Uninstall-Module. If that fails, it tries to remove the module directory directly.
 
    .PARAMETER Name
    Specifies the name of the module to uninstall.
 
    .PARAMETER Force
    Forces the uninstallation of the module.
 
    .EXAMPLE
    Uninstall-IntegrisModuleDependency -Name "ModuleName" -Force
    Attempts to uninstall the specified module with force.
 
    .NOTES
    The function checks if the module is installed and attempts to uninstall it using different methods.
    #>


    PARAM (
        [Parameter(Mandatory)]
        [String]$Name,
        [Parameter]
        [Switch]$Force
    )

    $InstalledModules = Get-Module -ListAvailable -Name $Name -ErrorAction SilentlyContinue
    
    IF ($InstalledModules) {
        TRY {
            Write-Host "Attempting to Uninstall Module using Uninstall-Module: $($Name)"
            $UninstallJob = Start-Job -ScriptBlock {
                $InstalledModules | Uninstall-Module
            }

            Wait-Job -Job $UninstallJob -Timeout 30
    
            $InstalledModules = Get-Module -ListAvailable -Name $Name -ErrorAction SilentlyContinue
        }
        CATCH {}

        IF ($InstalledModules) {
            Write-Host "Attempting to Uninstall Module using Remove-Item: $($Name)"
            $ModuleParentPath = ($InstalledModules.Path -split "\\$($Name)")[0]
            $PSModulePaths = $env:PSModulePath -split ";"
            IF ($PSModulePaths -eq $ModuleParentPath) {
                $ModuleFullPath = "$($ModuleParentPath)\$($Name)"
        
                Write-Host "Removing Path: $($ModuleFullPath)"
                Remove-Item -Recurse -Path $ModuleFullPath -Force -ErrorAction SilentlyContinue

                $InstalledModules = Get-Module -ListAvailable -Name $Name -ErrorAction SilentlyContinue
            }
            ELSE {
                Write-Error "Error Uninstalling $($Name) Module. It is not installed under one of the PSModulePath directories: $($env:PSModulePath)"
            }
        }
        ELSE {
            Write-Host "Successfully uninstalled Module: $($Name)"
        }
    }
    ELSE {
        Write-Host "Module is not installed: $($Name)"
    }
}