Public/Install-OriAzBopPrerequisite.ps1

<#
.SYNOPSIS
    Install modules required from PSGallery
.DESCRIPTION
    Install modules required from PSGallery
 
.PARAMETER Name
    Specifies the exact names of modules to install from the online gallery. The module name must match the module name in the repository.
 
.PARAMETER Guid
    GUID of the mmodule
 
.PARAMETER MaximumVersion
    Maximum module version
 
.PARAMETER RequiredVersion
    Required module version
 
.PARAMETER Version
    Most likely minimum module version
 
.PARAMETER PreRelease
    Name of PreRelease
     
.PARAMETER SkipImport
    When is set Import-Module will be skipped
 
.PARAMETER AllowClobber
    When is set AllowClobber will be used
 
.PARAMETER SkipPublisherCheck
    When is set SkipPublisherCheck will be used
 
.PARAMETER SkipPublisherCheck
    When is set SkipPublisherCheck will be used
 
.PARAMETER AllowPrerelease
    When is set AllowPrerelease will be used
.PARAMETER Proxy
    Use it when is required to use proxy while accessing the repository
.PARAMETER ProxyCredential
    Use it when is required to use proxy with credential
 
.EXAMPLE
    Install-OriAzBopPrerequisite -Name PowerShellGet -MinimumVersion 2.2.3
#>

function Install-OriAzBopPrerequisite {
    [CmdLetBinding()]
    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 = "Minimum module version")]
        [Alias('Version')]
        [Version] $MinimumVersion,

        [Parameter(Mandatory = $false, HelpMessage = "Name of PreRelease")]
        [String] $PreRelease,        

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

        [Parameter(Mandatory = $false, HelpMessage = "When is set AllowClobber will be used.")]
        [switch] $AllowClobber,
        
        [Parameter(Mandatory = $false, HelpMessage = "When is set SkipPublisherCheck will be used.")]
        [switch] $SkipPublisherCheck,
        
        [Parameter(Mandatory = $false, HelpMessage = "When is set AllowPrerelease will be used.")]
        [switch] $AllowPrerelease,

        [Parameter(Mandatory = $false, HelpMessage = "Use it when is required to use proxy while accessing the repository")]
        [Uri] $Proxy = $null,
    
        [Parameter(Mandatory = $false, HelpMessage = "Use it when is required to use proxy with credential")]
        [PSCredential] $ProxyCredential = $null
    
    )
    $ErrorActionPreference = 'Stop'
    Write-Verbose -Message ("[ START: {0}:{1} (v.{2}) ]" -f $Local:MyInvocation.MyCommand.Source, $Local:MyInvocation.MyCommand.Name, $Local:MyInvocation.MyCommand.Version)
    foreach ($arg in $PSBoundParameters.GetEnumerator()) {
        if ([string]::IsNullOrEmpty($arg.Value)) {
            Write-Debug -Message ("[null] {0}: {1}" -f $arg.Key, $arg.Value) -ErrorAction SilentlyContinue 
        }
        else {
            Write-Debug -Message ("[{2}] {0}: {1}" -f $arg.Key, $arg.Value, $arg.Value.GetType().Name) -ErrorAction SilentlyContinue 
        }
    }

    if ($SkipImport.IsPresent) {
        Write-Verbose "SkipImport: true"
    }
    else {
        Write-Verbose "SkipImport: false"
    }
    if ($AllowClobber.IsPresent) {
        Write-Verbose "AllowClobber: true"    
    }
    else {
        Write-Verbose "AllowClobber: false"           
    }
    if ($SkipPublisherCheck.IsPresent) {
        Write-Verbose "SkipPublisherCheck: true"    
    }
    else {
        Write-Verbose "SkipPublisherCheck: false"           
    }
    if ($AllowPrerelease.IsPresent) {
        Write-Verbose "AllowPrerelease: true"    
    }
    else {
        Write-Verbose "AllowPrerelease: false"           
    }

    $InstallParam = @{ 
        Name = $Name 
    }

    if (![string]::IsNullOrEmpty($Proxy)) {
        $InstallParam += @{ Proxy = $Proxy }
    }
    if (![string]::IsNullOrEmpty($ProxyCredential)) {
        $InstallParam += @{ ProxyCredential = $ProxyCredential }
    }

    if (![string]::IsNullOrEmpty($RequiredVersion)) {
        if ([string]::IsNullOrEmpty($PreRelease)) {
            $InstallParam += @{ RequiredVersion = $RequiredVersion }
        }
        else {
            $InstallParam += @{ RequiredVersion = '{0}-{1}' -f $RequiredVersion, $PreRelease }
        }
    }

    if (![string]::IsNullOrEmpty($MaximumVersion)) {
        $InstallParam += @{ MaximumVersion = $MaximumVersion }
    }
    if (![string]::IsNullOrEmpty($MinimumVersion)) {
        $InstallParam += @{ MinimumVersion = $MinimumVersion }
    }

    $AllInstalled = Get-Module -Name $Name -ListAvailable | Sort-Object -Property Version -Descending 
    $Installed = $AllInstalled | Select-Object -First 1
    $installRequired = $false
    if ([string]::IsNullOrEmpty($Installed)) {
        Write-Debug "The module $Name is not installed."
        $installRequired = $true
    }
    elseif (![string]::IsNullOrEmpty($Installed.Version)) {

        [Version] $InstalledVersion = $Installed.Version

        if (![string]::IsNullOrEmpty($RequiredVersion) `
                -and (
                -not($InstalledVersion -eq $RequiredVersion) `
                    -or ($InstalledVersion -eq $RequiredVersion `
                        -and ![string]::IsNullOrEmpty($Installed.PrivateData) `
                        -and ![string]::IsNullOrEmpty($Installed.PrivateData.PSData) `
                        -and ![string]::IsNullOrEmpty($Installed.PrivateData.PSData.Prerelease) `
                        -and ![string]::IsNullOrEmpty($PreRelease) `
                        -and $PreRelease -ne $Installed.PrivateData.PSData.Prerelease) `
            ) `
        ) {
            Write-Debug "The module $Name is installed in version [$InstalledVersion] PreRelase[$($Installed.PreRelease)], but required version is [$RequiredVersion] PreRelease[$PreRelease]."
            $installRequired = $true
        }


        if (![string]::IsNullOrEmpty($MaximumVersion) -and $InstalledVersion -gt $MaximumVersion) {
            Write-Debug "The module $Name is installed in version $InstalledVersion, but maximal version is $MaximumVersion."
            $TryFindTheVersion = $AllInstalled | Where-Object { $_.Version -eq $MaximumVersion }
            if ([string]::IsNullOrEmpty($TryFindTheVersion)) {
                $installRequired = $true
            }
            
        } 

        if (![string]::IsNullOrEmpty($MinimumVersion) -and $InstalledVersion -lt $MinimumVersion) {
            Write-Debug "The module $Name is installed in version $InstalledVersion, but minimal version is $MinimumVersion."
            $installRequired = $true
        } 
    }


    # The SkipPublisherCheck has been added due to new version of PowerShellGet 2.2.4 with dependency on PackageManagement 1.4.6
    # The PackageManagement 1.4.6 is quite every where and has been already required while instalation of PowerShellGet 2.2.3
    # However while the installation process is the PackageManagement 1.4.6 already loaded
    # and is not possible to override PackageManagement (it is cycle)
    # The solution is the SkipPublisherCheck flag
    if ($SkipPublisherCheck.IsPresent) {
        $InstallParam += @{ 
            SkipPublisherCheck = $True 
        }
    }
    if ($AllowClobber.IsPresent) {
        $InstallParam += @{ 
            AllowClobber = $True 
        }
    }
    if ($AllowPrerelease.IsPresent) {
        $InstallParam += @{ 
            AllowPrerelease = $True 
        }
    }
    

    if ($installRequired) {
        Invoke-OriAzExrExceptionRetry `
            -ListedExceptions @('Access to the path*is denied.') `
            -ScriptBlockToRun {
            Install-Module `
                @InstallParam `
                -Repository PSGallery `
                -Force `
                -Confirm:$false `
                -Verbose:$VerbosePreference `
                -Debug:$DebugPreference 
        }
    }
    
    if ($SkipImport.IsPresent) {
        Write-Debug "Skip of Import-Module"
    }
    else {

        $ImportedParam = @{ 
            ModuleName = $Name 
        }
        $ImportParam = @{
            Name = $Name
        }
        if (![string]::IsNullOrEmpty($MinimumVersion)) {
            $ImportedParam += @{ ModuleVersion = $MinimumVersion }
        }
        if (![string]::IsNullOrEmpty($MaximumVersion)) {
            $ImportedParam += @{ MaximumVersion = $MaximumVersion }
        }
        if (![string]::IsNullOrEmpty($RequiredVersion)) {
            $ImportedParam += @{ RequiredVersion = $RequiredVersion }
        }

        Write-Debug "Load of imported modules [$(ConvertTo-Json -InputObject $ImportedParam)] "

        if ($ImportedParam.ContainsKey("ModuleName") -and $ImportedParam.Count -gt 1) {
            [Microsoft.PowerShell.Commands.ModuleSpecification] $FullyQualifiedName = $ImportedParam
            $LoadedModules = Get-Module -FullyQualifiedName $FullyQualifiedName
            # Write-Debug "LoadedModules[$(ConvertTo-Json -InputObject $LoadedModules)] "
        }
        else {
            $LoadedModules = $null
        }

        if (-not([string]::IsNullOrEmpty($LoadedModules))) {
            Write-Debug "The required module is already loaded. Import skipped."
        }
        else {
            Write-Debug "Load of imported modules at least with same name. [$Name]"
            $LoadedAtLeastModuleName = Get-Module -Name $Name
            Write-Debug "LoadedAtLeastModuleName [$(ConvertTo-Json -InputObject $LoadedAtLeastModuleName -Depth 1)] "
            if (-not([string]::IsNullOrEmpty($LoadedAtLeastModuleName))) {
                Write-Warning "The required module is already loaded, but in different version Name:[$($LoadedAtLeastModuleName.Name)], Version:[$($LoadedAtLeastModuleName.Version)]. Import skipped."
            }
            else {
                $ImportParam = @{
                    Name = $Name
                }
                if (![string]::IsNullOrEmpty($MinimumVersion)) {
                    $ImportParam += @{ MinimumVersion = $MinimumVersion }
                }
                if (![string]::IsNullOrEmpty($MaximumVersion)) {
                    $ImportParam += @{ MaximumVersion = $MaximumVersion }
                }
                if (![string]::IsNullOrEmpty($RequiredVersion)) {
                    $ImportParam += @{ RequiredVersion = $RequiredVersion }
                }
                Write-Debug "Import paramters ImportParam: [$(ConvertTo-Json -InputObject $ImportParam)]"
                Import-Module @ImportParam `
                    -ErrorAction SilentlyContinue `
                    -Verbose:$VerbosePreference `
                    -Debug:$DebugPreference 
            }
        }

        

    }

    
    Write-Verbose -Message ("[ END: {0} ]" -f $Local:MyInvocation.MyCommand.Name)
}