Functions/Import-ExternalModule.ps1
<#
.SYNOPSIS This function installs and imports an external module. #> 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) { $installedVersions = (Get-Module -ListAvailable -Name $moduleName).Version $installedVersions = $installedVersions | ForEach-Object -Process { $_.ToString() } 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 { if (Get-Module -ListAvailable $moduleName) { Write-Information "$($moduleName) is already installed." } else { Install-Module $moduleName -Force -AllowClobber -Scope CurrentUser Write-Information "$($moduleName) has been installed." } } # Import the module if ($requiredVersion) { Import-Module $moduleName -RequiredVersion $requiredVersion -Force -Global Write-Information "Imported $($moduleName) version $($requiredVersion)." } else { Import-Module $moduleName -Force -Global Write-Information "Imported $($moduleName)." } } catch { Write-Error "Exception occurred on line $($_.InvocationInfo.ScriptLineNumber): `r`n$($_.Exception.Message)" } finally { $InformationPreference = $previousInformationPreference } } |