PowerShell Module Manifest - automatically loading a Required Module

Andy Schneider picture Andy Schneider · Mar 30, 2011 · Viewed 13.8k times · Source

I am creating a module that depends on several other modules that I need loaded into the global environment. I tried creating a script and using ScriptsToProcess to import the modules, but it looks like the check for RequiredModules happens before ScriptstoProcess runs.

Is there a nice, clean way in a Module Manifest to both Require a module and load it automatically if its not already loaded? If the module could not be loaded, then the RequiredModule would throw an error.

Answer

Jaykul picture Jaykul · Mar 30, 2011

In PowerShell 3 and up, RequiredModules are automatically loaded

It's also the only way to make sure people using PowerShellGet (i.e. the PowerShell Gallery) install your dependencies, if you're going to distribute the module.

It would still fail if the required modules are missing, but otherwise works exactly the way you'd wish it to.

In PowerShell 2, there's no way to automatically load RequiredModules

In either case, users can manually load the requirements by typing Import-Module RequiredModule, YourModule -- they won't get a second instance if it's already imported ...

You can also specify the module in NestedModules instead. Even in PowerShell 2, those get loaded "inside" your module, but don't seem to negatively affect resources when they're already loaded. However, as @JasonMArcher reminded me, in PowerShell 2, NestedModules get unloaded along with your module if your module gets unloaded (via Remove-Module), and this happens even if they were pre-loaded separately by the user, which can end up producing really weird bug reports since your users won't expect that.

The other option, which works in all versions of PowerShell, is to call Import-Module at the top of your module (in a psm1 script, after checking to make sure the module's not already loaded) with the -ErrorAction Stop set so that the import of your module will fail if the import of the dependent module fails.

if (!(Get-Module Dependency)) { ## Or check for the cmdlets you need
    ## Load it nested, and we'll automatically remove it during clean up
    Import-Module Dependency -ErrorAction Stop
}

Actually, if you wanted to check for versions ...

if (!(Get-Module Dependency | Where { $_.Version -ge "2.5" )) { 
    ## Load version 2.5 (or newer), or die 
    Import-Module Dependency -Version 2.5 -ErrorAction Stop
}

Just remember that this doesn't serve as documentation, so if you distribute the module, your users will not know about the dependencies.