Importing Modules

Sometimes, it can be difficult to streamline ways of efficiently loading modules or making sure they’re already loaded so that you code is optimized and runs quickly.

Here is an example of how I import modules.

CLS

#List the modules we want to load 1 per line
$LoadModules = @'
PoshRSJob
Proxx.SNMP
ImportExcel
VMware.PowerCLI
'@.Split("`n").Trim()

ForEach($Module in $LoadModules) 
{
    #Check if Module is Installed
    if($NULL -eq (Get-Module -ListAvailable $Module))
    {
        #Install Module
        Install-Module -Name $Module -Scope CurrentUser -Confirm:$False -Force
        #Import Module
        Import-Module $Module
    }

    #Check if Module is Imported
    if($NULL -eq (Get-Module -Name $Module))
    {
        #Install Module
        Import-Module $Module
    }
}

Similarly if you would like to load modules remotely you can do something like this:

CLS

#List the remote module you want to load and the server you want to load it from
$LoadRemoteModules = @'
STProtect, server1234
'@.Split("`n").Trim()

ForEach($RemoteModuleIfo in $LoadRemoteModules)
{
    #Clear each session for every new module
    $Session = $NULL

    #Seperate the Module from the Server
    $RemoteModule = ($RemoteModuleIfo -split ",").Trim()[0]
    $RemoteModuleServer = ($RemoteModuleIfo -split ",").Trim()[1]

    if(($NULL -eq ((Get-PSSession).ComputerName)) -OR (((Get-PSSession).ComputerName) -ne $RemoteModuleServer))
    {
        $Session = New-PSSession -ComputerName $RemoteModuleServer -Authentication Kerberos
        Invoke-Command -Session $Session -ScriptBlock { Import-Module $using:RemoteModule }
    }

    if($NULL -eq((Get-Module *) | Where-Object { ($_.Description -like "*$RemoteModuleServer*" ) }).ExportedCommands)
    {
        Import-PSSession -Session $Session -Module $RemoteModule -AllowClobber | Out-Null
    }
}