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

I have a script I want to use interactively from a PowerShell prompt. The script should use the local script module.

I do not see how to import / use the module so that it does not remain loaded in the current session.

Example

Module (MyModule.psm1) ...

function Test-Method { write-host "Test-Method invoked" } 

... and a script (script.ps1)

 Import-Module .\MyModule Test-Method 

Now run the script at the PowerShell prompt ...

 PS C:\temp> Get-Module | % {$_.Name} Microsoft.PowerShell.Management Microsoft.PowerShell.Utility PS C:\temp> .\script.ps1 Test-Method invoked PS C:\temp> Get-Module | % {$_.Name} Microsoft.PowerShell.Management Microsoft.PowerShell.Utility MyModule 

How can my script import and use MyModule.psm1 without loading it into the current call session? Considering that the call may have already imported the module and would not like to unload it using the script (therefore, simply removing the module upon completion of the script is not very good).

I thought that instead of importing it, instead of importing it, I want the module to be dot-sourcing, but I need the module for the reasons described in PowerShell Import-Module vs Dot Sourcing

+6
source share
3 answers

As far as I can tell, you are not getting this automatic cleanup mode from the "script" importing the module. OTOH, if you import a module from another module when the parent module is removed, any imported modules will be deleted if there are no other modules using them (or if ipmo-global is not specified).

+1
source

It looks like you already described what you wanted in the pseudo-code. Here it is in the actual code:

 $checkCmds = Get-Commands -Module MyModule Import-Module MyModule # Do stuff here . . . # unload only if we loaded it if ($checkCmds -eq $null) { Remove-Module MyModule } 
+6
source

You can import a module using -Scope local to restrict the module to a script scope. If the module is also loaded into the global scope, it will be available after the script exits.

-2
source

Source: https://habr.com/ru/post/954982/


All Articles