Skip to main content

A helper function to import the specified PowerShell module if it hasn't already been loaded, or download and install it from the PowerShell Gallery if it doesn't exist.

# From https://stackoverflow.com/a/51692402
function Load-Module
{
    param(
        [ValidateNotNullOrEmpty()]
        [String]
        $Name,

        [ValidateSet('AllUsers', 'CurrentUser')]
        [String]
        $Scope
    )

    # If module is imported say that and do nothing
    if (Get-Module | Where-Object { $_.Name -eq $Name })
    {
        Write-Host "Module '$Name' is already imported."
    }
    else
    {
        # If module is not imported, but available on disk then import
        if (Get-Module -ListAvailable | Where-Object { $_.Name -eq $Name })
        {
            Write-Host "Importing installed module '$Name'"
            Import-Module $Name
        }
        else
        {
            # If module is not imported, not available on disk, but is in online gallery then install and import
            if (Find-Module -Name $Name | Where-Object { $_.Name -eq $Name })
            {
                if ($Scope)
                {
                    Write-Host "Installing module '$Name' from the gallery under the '$Scope' scope"
                    Install-Module -Name $Name -Force -Scope $Scope
                }
                else
                {
                    Write-Host "Installing module '$Name' from the gallery under the default scope"
                    Install-Module -Name $Name -Force
                }

                Write-Host "Importing newly installed module '$Name' from the gallery"
                Import-Module $Name
            }
            else
            {
                # If the module is not imported, not available and not in the online gallery then abort
                # Write-Host "Module '$Name' not imported, not available and not in an online gallery, exiting."
                # exit 1
                throw "Module '$Name' could not be imported, and is not available from the online PowerShell Gallery. Exiting."
            }
        }
    }
}

# --------------------------------
# Example usage
# --------------------------------

# To load or install the module
Load-Module -Name 'IISAdministration'

# To remove the module from the current session
Remove-Module 'IISAdministration' -Force

# To uninstall the module from the system
Uninstall-Module 'IISAdministration' -Force