Forum Discussion
Function disappears after Import-Module
Hi, Dirk.
I haven't tested this but my intuition says it's a scoping issue.
When you import the module in your outer script (start.ps1), the module is imported into its own scope and linked to that outer script's session.
When you then launch the inner script (calledsscript_repro.ps1), I expect that the relationship between the outer script and the module is destroyed when the module is being unloaded courtesy of using the "-Force" parameter.
The module then loads into the inner script, with the module's session now linked only to the inner script's session, leaving the outer script unaware of the module and its exported functions.
Because the module is now only linked to the inner script, when that inner script finishes, the module is once again automatically unloaded as it's no longer in scope for the outer script, to which execution control is returned, and any further calls to that module's exported functions ought to fail.
I expect that you can keep the "-Force" in the outer script, but you should not use "-Force" in any inner/nested scripts.
You can read more about scopes here:
I'm not actually sure why you're loading the module in the inner script at all given it will inherit access to the module from the outer script - the "Local" parameter won't change that. But certainly you can, just not in conjunction with the "-Force" parameter.
Cheers,
Lain
Hi Lain,
Your explanation sounds very reasonable. So it looks like the function is the one which creates a scope, so that it does not work after leaving the function.
The reason why I import the module in both scripts: I can call both of the scripts also standalone.
The reason why I use the Import-Module with -Force is for debugging and development reason. Without -Force I have the following issue:
- I start powershell or "Visual Studio Code"
- execute a ps1, which imports a psm1
- change code in the psm1
- execute the same ps1 again
In this case still the unchanged code in psm1 is executed. In case I use the Import-Module with -Force it is reloaded and the changed code is executed.
I just had an idea how to resolve it . I execute the called script with a new powersehll.exe, like this:
function Invoke-ScriptFromFunction
{
Write-Host "THIS WILL CAUSE THE ISSUE"
. "C:\tmp\CalledScript_repro.ps1"
}
function Invoke-PowershellToExecuteScriptFromFunction
{
Write-Host "THIS WILL NOT CAUSE ANY ISSUE"
powershell.exe -File "C:\tmp\CalledScript_repro.ps1"
}
The new exe of course resolves the scoping stuff, but needs some more performance.
But I am still wondering, why there is not easy way to import and remove a module, without impacting calling scripts. Especially when I do not know, if my script will be called by another one after I developed it.
But thanks for the hint.
Cheers,
Dirk