How can I use a PowerShell module in a script without leaving the module loaded in the user’s session?

Question:

I have a script I wish to use interactively from the PowerShell prompt. The script needs to use a local script module.

I cannot see how to import/use the module such that it’s not left loaded in the current session.

Example

A module (MyModule.psm1)…

… and a script (script.ps1)

Now running the script at the PowerShell prompt …

How can my script import and use MyModule.psm1 without it being left loaded in the caller’s current session? Bearing in mind that the call may have already imported the module and would not want it unloaded by the script (so simply removing the module at the completion of the script is not really good enough).

I’ve considered dot-sourcing the module rather than importing it, but I want the module for the reasons covered in PowerShell Import-Module vs Dot Sourcing

Answer:

As far as I can tell, you don’t get that automatic cleanup behavior from a “script” importing a module. OTOH if you import a module from within another module, when the parent module is removed then any modules it imported will be removed if there are no other modules using them (or unless ipmo -global was specified).

Source:

How can I use a PowerShell module in a script without leaving the module loaded in the user’s session? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply