Public/Invoke-specRequiredModule.ps1

Function Invoke-specRequiredModule {
    param (
        [string]$ModuleName,
        [string]$ModuleVersion
    )

    Write-Host "Checking for required module" -ForegroundColor Darkcyan
    # Remove the module if it is already loaded
    Remove-Module $ModuleName -ea SilentlyContinue

    # Check to see if the required module version is already installed, if not, install and import it
    $module = Get-Module -ListAvailable -Name $modulename -ErrorAction SilentlyContinue | ? { $_.Version -eq $moduleversion }

    if ($null -eq $module) {
        Write-Host "$ModuleName version $moduleVersion requires installing" -ForegroundColor Darkgray
        Write-Host "Sending ping request to www.google.com to check internet connectivity." -ForegroundColor DarkGray
        $result = Test-specInternetConnectivity
        if ($result -eq $false) {
            Write-Host "Internet is not accessible, please check your internet connection" -ForegroundColor DarkYellow
            exit
        }

        try {
            Write-Host "Internet is accessible" -ForegroundColor DarkGreen
            Write-Host "Installing..." -ForegroundColor DarkGray
            Install-Module -Name $ModuleName -Force -AllowClobber -Scope AllUsers -RequiredVersion $moduleVersion -Repository PSGallery -ea Stop
            Write-Host "Module $ModuleName version $moduleVersion installed successfully" -ForegroundColor DarkGray
        } catch {
            Write-Host "`nFailed to install module $ModuleName version $moduleVersion" -ForegroundColor DarkYellow
            Write-Host "Error: $_" -ForegroundColor DarkYellow
            exit
        }

        Write-Host "`Importing module $ModuleName version $moduleVersion" -ForegroundColor Darkgray
        try {
            Import-Module -Name $ModuleName -RequiredVersion $moduleVersion -DisableNameChecking -ea stop
            Write-Host "Module $ModuleName version $moduleVersion imported successfully`n" -ForegroundColor DarkGreen
        } catch {
            Write-Host "Failed to import module $ModuleName version $moduleVersion" -ForegroundColor DarkYellow
            Write-Host "Error: $_" -ForegroundColor DarkYellow
            exit
        }
    } else {
        Write-Host "Module $ModuleName version $moduleVersion already installed" -ForegroundColor DarkGray
        Write-Host "Importing module $ModuleName version $moduleVersion" -ForegroundColor Darkgray
        try {
            Import-Module -Name $ModuleName -RequiredVersion $moduleVersion -DisableNameChecking -ea stop
            Write-Host "Module $ModuleName version $moduleVersion imported successfully`n" -ForegroundColor DarkGreen
        } catch {
            Write-Host "Failed to import module $ModuleName version $moduleVersion" -ForegroundColor DarkYellow
            Write-Host "Error: $_" -ForegroundColor DarkYellow
            exit
        }
    }
}