Private/Invoke-ModuleInstall.ps1

<#
.SYNOPSIS
    Install module with dependent modules in required version
.PARAMETER Name
    Exact name of the module
.PARAMETER Guid
    GUID of the mmodule
.PARAMETER MaximumVersion
    Maximum module version
.PARAMETER RequiredVersion
    Required module version
.PARAMETER Version
    Most likely minimum module version
.PARAMETER Credential
    Credential to repository
.PARAMETER Repository
    Name of the repository
.PARAMETER SkipImport
    When is set import-module will be skipped.
 
#>

function Invoke-ModuleInstall {
    [CmdLetBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Exact name of the module")]
        [string] $Name,
    
        [Parameter(Mandatory = $false, HelpMessage = "GUID of the mmodule")]
        [string] $Guid,
    
        [Parameter(Mandatory = $false, HelpMessage = "Maximum module version")]
        [Version] $MaximumVersion,
    
        [Parameter(Mandatory = $false, HelpMessage = "Required module version")]
        [Version] $RequiredVersion,
    
        [Parameter(Mandatory = $false, HelpMessage = "Most likely minimum module version")]
        [Version] $Version,

        [Parameter(Mandatory=$false, HelpMessage = "Repository Credential")]
        [PSCredential] $Credential = $null,

        [Parameter(Mandatory=$false, HelpMessage = "Repository name")]
        [string] $Repository = $null,

        [Parameter(Mandatory = $false, HelpMessage = "When is set import-module will be skipped.")]
        [switch] $SkipImport

    )
    $ErrorActionPreference = 'Stop'
    Write-Verbose '-- begin - Invoke-ModuleInstall --'
    Write-Verbose "Name: $Name"
    Write-Verbose "Guid: $Guid"
    Write-Verbose "MaximumVersion: $MaximumVersion"
    Write-Verbose "RequiredVersion: $RequiredVersion"
    Write-Verbose "Version: $Version"
    Write-Verbose "Repository: $Repository"
    if($SkipImport.IsPresent) {
        Write-Verbose "SkipImport: True"
    } else {
        Write-Verbose "SkipImport: False"
    }

    $toReturn = $null

    $InstallModuleParam = @{ Name = $Name }
    if (![string]::IsNullOrEmpty($Guid)) {
        $InstallModuleParam += @{Guid = $Guid }
    }
    if (![string]::IsNullOrEmpty($MaximumVersion)) {
        $InstallModuleParam += @{MaximumVersion = $MaximumVersion }
    }
    if (![string]::IsNullOrEmpty($RequiredVersion)) {
        # Only when is set RequiredVersion we do need add Prefix into Import-Module paramters
        $InstallModuleParam += @{RequiredVersion = $RequiredVersion }
    }
    if (![string]::IsNullOrEmpty($Version)) {
        $InstallModuleParam += @{Version = $Version }
    }
    if($null -ne $Credential) {
        $InstallModuleParam += @{Credential = $Credential}
    }
    if($null -ne $Repository) {
        $InstallModuleParam += @{Repository = $Repository}
    }

    Write-Verbose ($InstallModuleParam |Out-String)
    $FoundModule = Find-ModuleForInstall @InstallModuleParam

    if (![String]::IsNullOrEmpty($FoundModule) -and ![String]::IsNullOrEmpty($FoundModule.Repository)) {
        Write-Verbose "Found: [$($FoundModule.Repository)] is not null Version [$($FoundModule.Version)]"
    } else {
        Write-Verbose "Module [$Name] not found or Repository is not set."
    }

    # Create hastable for check of installed modules
    $GetInstalledParam = $InstallModuleParam.Clone()
    if ($GetInstalledParam.ContainsKey('Credential')) {
        $GetInstalledParam.Remove('Credential')           
    }
    if ($GetInstalledParam.ContainsKey('Repository')) {
        $GetInstalledParam.Remove('Repository')           
    }

    $ModuleInstalled = Get-InstalledModule @GetInstalledParam -ea SilentlyContinue
    if(-not([string]::IsNullOrEmpty($ModuleInstalled)) -and -not([string]::IsNullOrEmpty($ModuleInstalled.Version))) {
        Write-Verbose "The module $Name is alredy installed in version $($ModuleInstalled.Version)"
    } else {
        Write-Verbose "The module $Name is NOT installed"
    }


    # Versions should be compared in proper type
    # Note: Original ($ModuleInstalled.Version -lt $FoundModule.Version) is not working
    if ([string]::IsNullOrEmpty($ModuleInstalled) `
    -or [string]::IsNullOrEmpty($ModuleInstalled.Version) `
    -or [string]::IsNullOrEmpty($FoundModule.Version)`
    -or ([Version] $ModuleInstalled.Version -lt [Version] $FoundModule.Version) `
    ) {
        Write-Verbose "Install-Module param:"
        Write-Verbose (ConvertTo-Json  $InstallModuleParam)

        # Sometimes, specially on servers, the installation process is failing.
        # There has been spotted problems when more processes under the same user is trying to install same module in the same time,
        # but it can ge more general issue.
        # Therefore seems to be usefull to use the retry exeception funtion and collect such errors when simple retry can fix the problem.
        Invoke-OriAzExrExceptionRetry `
        -ListedExceptions @('Access to the path*is denied.') `
        -ScriptBlockToRun {
            Install-Module @InstallModuleParam `
            -Force `
            -Confirm:$false `
            -Verbose:$VerbosePreference `
            -Debug:$DebugPreference
        }

        # re-Load after the installation
        $ModuleInstalled = Get-InstalledModule @GetInstalledParam -ea SilentlyContinue 
    } else {
        Write-Verbose "Module aready exists"
        Write-Verbose ("Module is already installed on path: {0}" -f $ModuleInstalled.InstalledLocation)
    }

    $toReturn = Join-Path -Path $ModuleInstalled.InstalledLocation -ChildPath ('{0}.psd1' -f $ModuleInstalled.Name)
    Invoke-ResolveDependency `
    -InstalledLocation $ModuleInstalled.InstalledLocation `
    -Credential $Credential `
    -Repository $Repository `
    -SkipImport $SkipImport `
    -Verbose:$VerbosePreference `
    -Debug:$DebugPreference

    Write-Verbose '-- end - Invoke-ModuleInstall --'
    return $toReturn 
}