powershellmodulescope

Why does Import-Module import into the calling module's scope, while New-PSDrive creates a drive in the scope which called the module?


Per Import-Module's -Scope parameter documentation:

By default, when Import-Module cmdlet is called from the command prompt, script file, or scriptblock, all the commands are imported into the global session state. You can use the -Scope Local parameter to import module content into the script or scriptblock scope.

When invoked from another module, Import-Module cmdlet imports the commands in a module, including commands from nested modules, into the caller's session state. Specifying -Scope Global or -Global indicates that this cmdlet imports modules into the global session state so they're available to all commands in the session.

I don't fully understand the why of this behavior, but I do understand the what and have learned how to work with this. I will say that the documentation's language is a bit obtuse and ambiguously worded; this is stated much more plainly by mklement0 here.

Per New-PSDrive's -Scope parameter documentation:

Specifies a scope for the drive. The acceptable values for this parameter are: Global, Local, and Script, or a number relative to the current scope. Scopes number 0 through the number of scopes. The current scope number is 0 and its parent is 1. For more information, see about_Scopes.

Default value: Local

Creating a new PSDrive from within a module (ostensibly) does not follow the same logic as importing a module. The drive is accessible from the scope which called the module, even though the drive is created with the Local scope.

So to summarize:

That leaves me rather confused as to what meanings Global and Local actually have.

TL;DR: Import-Module and New-PSDrive seem to have very different interpretations and implementations of what Local and Global scope mean to them, and I'm just trying to understand why. I suspect this is a loaded question, given the nature of modules, and the need to export module functions/variables in order for them to be used in the calling scope. Modules themselves seem to have a unique pseudo-scope that I guess I don't fully understand.


Solution

  • As it turns out I was misinformed and the premise of the question is erroneous.

    As @mklement0 points out in the OP comments, New-PSDrive -Scope Local (the default) does in fact create a drive in the scope of the module, which is not accessible to the module's calling scope (without using -Scope Global).

    In my case, my custom module created a PSDrive in the local scope only if it doesn't already exist, but the code immeditately before it imported a module (the ConfigurationManager module), which created the same PSDrive in the Global scope during its import process, so I was under the mistaken impression that my locally scoped PSDrive was somehow being made available outside of the custom module's scope.