Private/Import-SpecPowerShellModule.ps1
Function Import-SpecPowerShellModule { <# .SYNOPSIS Imports a PowerShell module. .DESCRIPTION The Import-SpecPowerShellModule function imports a PowerShell module by name. It unloads any existing module with the same name and then imports the specified module. .PARAMETER Module The name of the module to import. This parameter accepts pipeline input. .INPUTS System.String .OUTPUTS None .EXAMPLE Import-SpecPowerShellModule -Module 'MyModule' Imports the 'MyModule' PowerShell module. .EXAMPLE 'Module1', 'Module2' | Import-SpecPowerShellModule Imports the 'Module1' and 'Module2' PowerShell modules using pipeline input. .NOTES - If the module is already imported, it is first removed and then re-imported to ensure a fresh import. - If an error occurs during the import process, an error message is displayed, and the function exits with a status code of 500. Author: owen.heaume Company: Specsavers Version: - 1.0 - 1.1 Multiple bugfixes picked up by Pester tests eg - did not support pipeline input correctly #> [cmdletbinding()] param ( [parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string]$Module, [string]$RequiredVersion = "" ) process { foreach ($m in $Module) { #if ([string]::IsNullOrEmpty($RequiredVersion) ) {$RequiredVersion -eq ""} write-host "Checking to see if module [$m] is already imported" -ForegroundColor DarkCyan $importResult = Get-Module -Name $m #-ErrorAction SilentlyContinue $version = $importResult.Version if ($importResult) { if ($importResult.Version -eq $RequiredVersion) { Write-Host "[$m] version [$($importresult.version)] is already imported and at the required version [$RequiredVersion]" -ForegroundColor DarkGreen write-host continue } Write-Host "[$m] is already imported" -ForegroundColor DarkGray write-host "Removing module from memory" -ForegroundColor DarkCyan $result = Remove-SpecPowerShellModule -module $m if ($result -eq 0 ) { write-host "Module removed successfully" -ForegroundColor DarkGreen } else { write-host "Module could not be removed from memory" -ForegroundColor DarkYellow } } else { Write-Host "[$m] is not already imported on this system" -ForegroundColor DarkGray } # Attempt to import module try { if ([string]::IsNullOrEmpty($RequiredVersion)) { write-host "Importing module [$m]" -ForegroundColor DarkCyan Import-Module $M -Force -Verbose:$false -ErrorAction stop write-host "Module imported successfully" -ForegroundColor DarkGreen } else { write-host "Importing module [$m] version [$RequiredVersion]" -ForegroundColor DarkCyan Import-Module $M -force -RequiredVersion $RequiredVersion -Verbose:$false -ErrorAction stop write-host "Module imported successfully" -ForegroundColor DarkGreen } write-host } catch [System.Exception] { Write-Error "ERROR - unable to import the $M module" Exit 500 } } } } |