Functions/Import-ExternalModule.ps1
<#
.SYNOPSIS This function installs and imports an external module. .DESCRIPTION This function installs and imports an external module. The use of this module is preferred over Install-Module and Import-Module when a specific version of a module is required as using Install-Module with both the -RequiredVersion and -Force parameters results in a re-download and re-installation every time, even if the required version is already installed, which results in unnecessary slowness. Import-ExternalModule removes this issue by skipping the installation if the required version is already installed. #> function Import-ExternalModule { [CmdletBinding(PositionalBinding=$true)] param ( # The name of the module to import. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$moduleName, # The required version of the module to import. [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [String]$requiredVersion, # Select whether to suppress messages. [Parameter(Mandatory=$false)] [Switch]$quiet ) # Suppress messages $previousInformationPreference = $InformationPreference if ($quiet) { $InformationPreference = "SilentlyContinue" } # Install and import the module try { # Install the module if ($requiredVersion) { # Retrieve installed versions of the module $installedVersions = (Get-ChildItem -Path "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules\$($moduleName)" ` -ErrorAction SilentlyContinue).Name # Check if the required version has already been installed if ($requiredVersion -notIn $installedVersions) { Install-Module $moduleName -RequiredVersion $requiredVersion -Force -AllowClobber -Scope CurrentUser Write-Information "$($moduleName) version $($requiredVersion) has been installed." } else { Write-Information "$($moduleName) version $($requiredVersion) is already installed." } } else { # Retrieve installed versions of the module $installedVersions = (Get-ChildItem -Path "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules\$($moduleName)" ` -ErrorAction SilentlyContinue).Name # Check if any version of the module has already been installed if ($installedVersions) { Write-Information "$($moduleName) is already installed." } else { Install-Module $moduleName -Force -AllowClobber -Scope CurrentUser Write-Information "$($moduleName) has been installed." } } # Import the module $userModulesPath = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules" if ($requiredVersion) { Import-Module -Name "$($userModulesPath)\$($moduleName)" -RequiredVersion $requiredVersion -Force -Global Write-Information "Imported $($moduleName) version $($requiredVersion)." } else { Import-Module -Name "$($userModulesPath)\$($moduleName)" -Force -Global Write-Information "Imported $($moduleName)." } } catch { Write-Error "Exception occurred on line $($_.InvocationInfo.ScriptLineNumber): `r`n$($_.Exception.Message)" } finally { $InformationPreference = $previousInformationPreference } } |