Public/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) {
            write-host "`n"
            $importedModules = Get-Module -Name $m #-ErrorAction SilentlyContinue
            $version = $importedModules.Version


            if ($importedModules) {
                Write-Verbose "The module '$m' is already imported."
                $imported = $true
            } else {
                Write-verbose "The module '$m' is not already imported."
                $imported = $false
            }

            # Attempt to import module
            try {
                # Unload any existing module if loaded already
                if ($imported) {
                    write-verbose "Unloading $Module..."
                    Remove-Module $M -Verbose:$false -Force -ErrorAction SilentlyContinue
                }

                if ($RequiredVersion -eq "" -or $RequiredVersion -eq $null) {
                    write-verbose "Importing module $m"
                    Import-Module $M -Force -Verbose:$false -ErrorAction stop
                } else {
                    write-verbose "Importing module version: $RequiredVersion..."
                    Import-Module $M -force -RequiredVersion $RequiredVersion -Verbose:$false -ErrorAction stop
                }
            } catch [System.Exception] {
                Write-Error "ERROR - unable to import the $M module"
                Exit 500
            }

            Write-Verbose "Import of Module was successful"
        }
    }
}