I have found that module auto-loading is unreliable. @briantist recommends explicitly importing required modules in finished code. This seems like good advice to me. The problem is I haven't found a reliable way to ensure that all required modules are explicitly imported.
Example
Supposed I have three modules with these dependencies:
m1.psm1 (depends on nothing)
m2.psm1 (calls functions in m1)
Suppose also that each of these modules has a set of automated tests that achieve 100% code coverage.
Running the tests for m2
only alerts you to a missing call to Import-Module m1
in the rare occurrence that PowerShell's auto-loading happens to fail to load m2
at the specific time you run the test. If you have several 10s of .psm1
files, the odds of missing a required Import-Module
increases dramatically.
Suppose I mistakenly omit Import-Module m1
in m2.psm1
(after all, it passed all the automated tests) and put these modules into production. Each time functions in m2
are executed there is a small chance that m1
will not auto-load. When m1
does not successfully auto-load, the script fails to execute correctly that time, but may well execute correctly the time before and the time after. This will make it rather difficult to diagnose the cause of problem.
How do you ensure that all modules a script or module depends on have been explicitly imported?
Clarification: The modules I am developing are mostly automations that will ultimately run unattended on a server. Accordingly, I need to ensure that the functions in the modules will execute quickly and correctly once they are deployed on a machine other than my development workstation.
It is, of course, possible to import all modules you know you need explicitly when you start the powershell session. However, the auto-loading mechanism still masks the case where you forgot to explicitly load a module you depend on.
You can also blindly load all modules at startup (I do this at some stages during development), but depending on that means a start-up time on the order of 10s of seconds that grows with the size of your module library. That startup time will likely become a problem because it will be incurred each time a script is executed.