Search code examples
powershellclassmoduleusing

Classes loaded as dependency in imported module are not imported into script


I have some PowerShell modules and scripts that looks something like this:

MyClassModule.psm1

class MyClass {
  #...
}

MyUtilityModule.psm1

using module MyClassModule

# Some code here

MyScript.ps1

using module MyUtilityModule

[MyClass]::new()

My questions are:

Why does this script fail if the class is imported as a dependency in MyUtilityModule?

Are imports always only local to the direct script they are imported into?

Is there any way to make them global for a using statement?

If it makes any difference I need to write with backwards compatibility to at least PowerShell version 5.1


Solution

  • This is all about scope. The user experience is directly influenced by how one loads a class. We have two ways to do so:

    1. import-Module

      Is the command that allows loading the contents of a module into the session.

      ... It must be called before the function you want to call that is located in that specific module. But not necessarly at the beginning/top of your script.

    2. Using Module

      ...

      The using statement must be located at the very top of your script. It also must be the very first statement of your script (Except for comments). This make loading the module ‘conditionally’ impossible.

    Comand Type, Can be called anywhere in script, internal functions, public functions, Enums, Classes

    Import-Module, Yes, No, Yes, No, No

    using Module, No, No, Yes, Yes, Yes

    See these references for further details

    How to write Powershell modules with classes https://stephanevg.github.io/powershell/class/module/DATA-How-To-Write-powershell-Modules-with-classes

    What is this Module Scope in PowerShell that you Speak of? https://mikefrobbins.com/2017/06/08/what-is-this-module-scope-in-powershell-that-you-speak-of