# Making PowerShellGallery modules Portable

Download PowerShellGallery modules with their dependencies for portable, offline installs when servers cannot reach the gallery directly.

blog

08 Sep 2019 fr

[Voir les images (3)](#pf-content-image-1-0)

I'm a big fan of **PowerShellGallery**. It's easy to use, Microsoft owned, a place to host your **PowerShell** modules. Every time I release a new PowerShell module, it's readily available for me or anyone with a single command **Install-Module**. No need to host it yourself, no need to prepare anything – **plug & play**. Additionally, if your **PowerShell** module has any dependencies, it will download and install them, so it directly works out of the box. But what if you can't use **PowerShellGallery**? What if you don't want to use **Install-Module** on 100 computers, but you prefer to do it in a more controlled way? What if your servers do not have internet connectivity?

### 💡 Making PowerShellGallery modules Portable

I usually would use **GitHub** sources and build it from that. This seems relatively easy till you find out your **PowerShell** module has seven other dependencies that you need to download and use. Additionally, if you download my modules from **GitHub**, they don't have any optimization that I usually do when publishing them to **PowerShellGallery**. Fortunately, there's a way to make **PowerShellGallery** modules portable. Below is a simple function that when given Module Name will download the module we requested with all it's dependencies to the specified folder. After that, it will import all those modules to memory, making it available to use.

```powershell
function Initialize-ModulePortable {
    [CmdletBinding()]
    param(
        [alias('ModuleName')][string] $Name,
        [string] $Path = $PSScriptRoot,
        [switch] $Download,
        [switch] $Import
    )
    function Get-RequiredModule {
        param(
            [string] $Path,
            [string] $Name
        )
        $PrimaryModule = Get-ChildItem -LiteralPath "$Path\$Name" -Filter '*.psd1' -Recurse -ErrorAction SilentlyContinue -Depth 1
        if ($PrimaryModule) {
            $Module = Get-Module -ListAvailable $PrimaryModule.FullName -ErrorAction SilentlyContinue -Verbose:$false
            if ($Module) {
                [Array] $RequiredModules = $Module.RequiredModules.Name
                if ($null -ne $RequiredModules) {
                    $null
                }
                $RequiredModules
                foreach ($_ in $RequiredModules) {
                    Get-RequiredModule -Path $Path -Name $_
                }
            }
        } else {
            Write-Warning "Initialize-ModulePortable - Modules to load not found in $Path"
        }
    }

    if (-not $Name) {
        Write-Warning "Initialize-ModulePortable - Module name not given. Terminating."
        return
    }
    if (-not $Download -and -not $Import) {
        Write-Warning "Initialize-ModulePortable - Please choose Download/Import switch. Terminating."
        return
    }

    if ($Download) {
        try {
            if (-not $Path -or -not (Test-Path -LiteralPath $Path)) {
                $null = New-Item -ItemType Directory -Path $Path -Force
            }
            Save-Module -Name $Name -LiteralPath $Path -WarningVariable WarningData -WarningAction SilentlyContinue -ErrorAction Stop
        } catch {
            $ErrorMessage = $_.Exception.Message

            if ($WarningData) {
                Write-Warning "Initialize-ModulePortable - $WarningData"
            }
            Write-Warning "Initialize-ModulePortable - Error $ErrorMessage"
            return
        }
    }

    if ($Download -or $Import) {
        [Array] $Modules = Get-RequiredModule -Path $Path -Name $Name | Where-Object { $null -ne $_ }
        if ($null -ne $Modules) {
            [array]::Reverse($Modules)
        }
        $CleanedModules = [System.Collections.Generic.List[string]]::new()

        foreach ($_ in $Modules) {
            if ($CleanedModules -notcontains $_) {
                $CleanedModules.Add($_)
            }
        }
        $CleanedModules.Add($Name)

        $Items = foreach ($_ in $CleanedModules) {
            Get-ChildItem -LiteralPath "$Path\$_" -Filter '*.psd1' -Recurse -ErrorAction SilentlyContinue -Depth 1
        }
        [Array] $PSD1Files = $Items.FullName
    }
    if ($Download) {
        $ListFiles = foreach ($PSD1 in $PSD1Files) {
            $PSD1.Replace("$Path", '$PSScriptRoot')
        }
        # Build File
        $Content = @(
            '$Modules = @('
            foreach ($_ in $ListFiles) {
                "   `"$_`""
            }
            ')'
            "foreach (`$_ in `$Modules) {"
            "   Import-Module `$_ -Verbose:`$false -Force"
            "}"
        )
        $Content | Set-Content -Path $Path\$Name.ps1 -Force
    }
    if ($Import) {
        $ListFiles = foreach ($PSD1 in $PSD1Files) {
            $PSD1
        }
        foreach ($_ in $ListFiles) {
            Import-Module $_ -Verbose:$false -Force
        }
    }
}
```

It's effortless but at the same time very useful. **Updating your disconnected environment** is much easier this way. You can quickly test something and **remove a folder** from your machine without having it installed.

```powershell
Initialize-ModulePortable -Name 'Testimo' -Download -Path $PSScriptRoot
```

[!\[PowerShell console output from Initialize-ModulePortable downloading the Testimo module into a portable folder.\](/wp-content/uploads/2019/09/img_5d7425edaae04.png)](/wp-content/uploads/2019/09/img_5d7425edaae04.png)[!\[Portable module bootstrap output showing Save-Module behavior while preparing the Testimo launcher script.\](/wp-content/uploads/2019/09/img_5d742614ce535.png)](/wp-content/uploads/2019/09/img_5d742614ce535.png)

As you can see on the screenshot above it looks like the command is Installing the module, but it's using **Save-Module** to download module to a given directory. After that, it creates a new **PS1** file and puts it into the primary folder. The file name is identical to the module name. The file has logic to read module **PSD1** file, check for **RequiredModules** section and import them in the order given in **PSD1**. Finally, script imports requested module.

[!\[Folder view with downloaded PowerShell modules and the generated Testimo.ps1 portable launcher script.\](/wp-content/uploads/2019/09/img_5d7425dc4cb25.png)](/wp-content/uploads/2019/09/img_5d7425dc4cb25.png)

If we check directory, we can see it **downloaded** nine modules to that folder. You can also see the file named Testimo**.ps1** which, when executed, will **Import all those modules** in hopefully proper order. That means you can then copy that folder anywhere, execute with **PS1** file that does all the hard work for you. After that all commands become available and you can use them as you would do after standard installation. Keep in mind that I've tested this on limited number of modules. It's possible I've skipped something when writting this. Current development version is located on GitHUB as part of [PSSharedGoods](https://github.com/EvotecIT/PSSharedGoods/blob/master/Public/Programs/Initialize-ModulePortable.ps1) module. Feel free to submit bugs if you find one.

## Projets associés

Projets liés aux tags, catégories et au contenu de cet article.

[Tous les projets](/fr/projets/)

Recherche des projets associés...

[Retour au blog](/blog)

## Articles associés

- [PowerBGInfo – PowerShell alternative to Sysinternals BGInfo](/fr/blog/powerbginfo-powershell-alternative-to-sysinternals-bginfo/)
- [Configuring Office 365 settings using PowerShell – The non-supported way](/fr/blog/configuring-office-365-settings-using-powershell-the-non-supported-way/)
- [Creating Office 365 Migration Diagram with PowerShell](/fr/blog/creating-office-365-migration-diagram-with-powershell/)

<!-- PowerForge markdown artifact sha256:BA77E30CBD9A365AA4BD0F45AB2ABF29416BDF1B694CEC56A7D2448FEDE095A4 -->
