Import-PSModule: Import PowerShell Modules

Topics: Archive - Toolkit Extensions
Developer
Jul 31, 2014 at 5:13 AM
This function uses Write-Log and Write-ErrorStack functions posted in separate threads under Toolkit Extensions.
Function Import-PSModule
{
    [CmdletBinding()]
    Param
    (
        [string]$Name
    )
    
    Begin
    {
        ${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
        $PSParameters = New-Object -TypeName PSObject -Property $PSBoundParameters
        
        Write-Log -Message "Function Start" -Component ${CmdletName} -Severity 1
        If (-not [string]::IsNullOrEmpty($PSParameters))
        {
            Write-Log -Message "Function invoked with bound parameters [$PSParameters]" -Component ${CmdletName} -Severity 1
        }
        Else
        {
            Write-Log -Message "Function invoked without any bound parameters" -Component ${CmdletName} -Severity 1
        }
    }
    Process
    {
        If (-not (Get-Module -Name $Name))
        {
            If (Get-Module -ListAvailable | Where-Object { $_.Name -eq $Name })
            {
                Try
                {
                    Write-Log -Message "Load PowerShell Module [$Name]" -Component ${CmdletName} -Severity 1
                    Import-Module -Name $Name -DisableNameChecking -ErrorAction 'Stop'
                    Return $true
                }
                Catch
                {
                    Write-Log -Message "Failed to load PowerShell module [$Name] `n$(Write-ErrorStack)" -Component ${CmdletName} -Severity 3
                    Return $false
                }
            } # end if module available then import
            Else
            {
                Write-Log -Message "PowerShell module [$Name] is not available for import. Failed to load PowerShell module [$Name]" -Component ${CmdletName} -Severity 3
                Return $false
            } # module not available
        } # end if module not available
        Else
        {
            Write-Log -Message "PowerShell Module [$Name] already loaded" -Component ${CmdletName} -Severity 1
            Return $true
        } # module already loaded
    }
    End
    {
        Write-Log -Message "Function End" -Component ${CmdletName} -Severity 1
    }
} # end function Import-PSModule