powershellmodulescope

PowerShell - how to import module in a script without polluting the global scope?


Inside a script, I import a module, for example

Import-Module -Name Test -Scope Local

I execute the script at the command prompt

test.ps1

Then, after the script finishes, I run Get-Module and the imported module shows up (though the functions, etc are not available).

Is it possible to prevent this without adding a Remove-Module? (would add complexity to my scripts so I'd rather avoid it)


Solution

  • As Mathias points out in the comments, the behavior is documented - surprising as it may be (emphasis added):

    Get-Module shows all modules loaded in the current session. This includes modules loaded locally in a descendant scope. Use Get-Command -Module modulename to see which members are loaded in the current scope.

    If Get-Command -Module <your-module-name-or-path> yields no output , the implication is that the module was imported locally in a descendent scope and that its members are not accessible in the calling scope.

    In other words:

    Caveat: