How to install module into Custom directory?

mit picture mit · Feb 27, 2017 · Viewed 7.4k times · Source

Currently we are installing some modules using the command below, but it installs modules in C:\Program Files\WindowsPowerShell\Modules.

Install-Module -Name XXX -RequiredVersion XXX -Repository XXX -Scope AllUsers

Our requirement is to install this module in the E:\Modules folder. For that I updated the PSModulePath environment variable as below. (https://msdn.microsoft.com/en-us/library/dd878350(v=vs.85).aspx)

$p = [Environment]::GetEnvironmentVariable("PSModulePath")
$p += ";E:\Modules"
[Environment]::SetEnvironmentVariable("PSModulePath",$p)

But it still installs in C:\Program Files\WindowsPowerShell\Modules.

How do I update PSModulePath to E:\Modules before installing modules?

Answer

Harry Sanderson picture Harry Sanderson · Oct 10, 2018

You can download the module zip manually using the Save-Module command.

Find-Module -Name 'XXX' -Repository 'PSGallery' | Save-Module -Path 'E:\Modules'

From here you can either import the module using a fully qualified name like so:

Import-Module -FullyQualifiedName 'E:\Modules\XXX'

Or by adding your destination folder to the PSModulePath like you did before.

$modulePath = [Environment]::GetEnvironmentVariable('PSModulePath')
$modulePath += ';E:\Modules'
[Environment]::SetEnvironmentVariable('PSModulePath', $modulePath)

You can then check if the module has been imported using the Get-Module cmdlet.


If you are using the Import-Module command it can get a bit painful, especially if you have lots of modules. So you could wrap the approach in a function like this:

function Install-ModuleToDirectory {
    [CmdletBinding()]
    [OutputType('System.Management.Automation.PSModuleInfo')]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        $Name,

        [Parameter(Mandatory = $true)]
        [ValidateScript({ Test-Path $_ })]
        [ValidateNotNullOrEmpty()]
        $Destination
    )

    # Is the module already installed?
    if (-not (Test-Path (Join-Path $Destination $Name))) {
        # Install the module to the custom destination.
        Find-Module -Name $Name -Repository 'PSGallery' | Save-Module -Path $Destination
    }

    # Import the module from the custom directory.
    Import-Module -FullyQualifiedName (Join-Path $Destination $Name)

    return (Get-Module)
}

Install-ModuleToDirectory -Name 'XXX' -Destination 'E:\Modules'