3

I started studying Powershell and was writing a module (psm1) in order to store my functions. Then I inserted this code in the module in order to reload the module when I modify it:

function reload
{
    Remove-Module init
    Import-Module F:\Script\init.psm1
}

The result of this function appears a little strange to me:

PS F:\Script> Get-Module

ModuleType Name                                ExportedCommands
---------- ----                                ----------------
Script     init                                {cpu, ie, lol, outlook...}
Manifest   Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}


PS F:\Script> reload
PS F:\Script> Get-Module

ModuleType Name                                ExportedCommands
---------- ----                                ----------------
Manifest   Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}


PS F:\Script>

Why the second command in the function has no effect? I also noticed that the module appears in the list if I insert "Get-Module" at the end of my function, just like the module "runs" in an other Powershell instance/session. If so, is there a way to make the effects persistent?

Thank you!

EDIT:

I temporarily solved by adding a parameter to the import function in order to specify the scope in which to load the module:

Import-Module F:\Script\init.psm1 -Global

Is this the right way to deal with scope?

2 Answers 2

2

Perhaps this come from the fact that function from modules are executed in the module scope.

Here under the red arrows show the scope resolution sequence.

F1 function call F2 function ans F2 function call a function Inside a module. The functions F1 and F2 take their vars in the default scope. The function FMOD use the module scope.

This can explain why Get-Module show Ini when called Inside the function.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your diagram, it's very useful. Now, how can I import the module in the right scope?
0

Rather than add a reload function, just use the -Force parameter where you originally use Import-Module. That will force the module to be re-imported, picking up any changes you've made to it since it was last imported.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.