Search code examples
powershell

How to `Import-Module` in PowerShell to parent session/process?


I store imports for my favourite modules in a myFavMods.ps1:

Import-Module a
Import-Module b
...

When running it like this the modules are not available in my session:

> ./myFavMods.ps1
> funFromModuleA
funFromModuleA: The term 'funFromModuleA' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

When running it using the . operator it works:

> . ./myFavMods.ps1
> funFromModuleA
Hurray this is funFromModuleA reporting!

Is it possible to have funFromModuleA available regardless of how I execute my script? Is it possible to Import-Module -Scope 'GlobalGlobalAllTheWayUp'?

What I know so far

Profile

I am aware of PowerShell profiles but I would like my favourite modules only available when imported explicitly.

Make the script inspect how it's being executed

I could use $MyInvocation.Line to check if the script is being invoke with a . but I would rather have it work always regardless of the way of invocation.

Import-Module -Scope

This can only be used to narrow down the scope to Local.


Solution

  • For this you might consider to create a module manifest that includes all your "funFrom" modules:

    .\myFavMods\a.psm1

    function funFromModuleA { 'Fun from module A.'}
    Export-ModuleMember -Function funFromModuleA
    

    .\myFavMods\a.psm1

    function funFromModuleB { 'Fun from module B.'}
    Export-ModuleMember -Function funFromModuleB
    

    New manifest

    The following command creates a new module manifest at .\myFavMods\myFavMods.psd1:

    New-ModuleManifest .\myFavMods\myFavMods.psd1  -NestedModules '.\a.psm1', '.\b.psm1'
    

    .\myFavMods\myFavMods.ps1

    In case you want to invoke the "funFrom" module from a PowerShell Script (.ps1 file):

    Import-Module $PSScriptRoot\..\myFavMods -Global
    

    Test

    .\myFavMods\myFavMods.ps1
    funFromModuleA
    Fun from module A.