Is module auto-loading meant to be reliable?

Question:

Environment

I have the following folder structure where I keep powershell modules:

There are about 50 folders and modules in c:\PsModules.

I have set environment variable PSModulePath to include c:\PsModules. This seems to meet the conditions for “well-formed modules” described in Microsoft’s documentation and this answer.

Symptoms

Sometimes Test-Function is not found automatically when calling it from ISE. In fact, on any given fresh launch of ISE, there are always some (seemlingly unpredictable) modules that are not found automatically. The failure to automatically find Test-Function, for example, looks like this:

At first glance, this seems to indicate that util.psm1 is not “well-formed”. If it were not “well-formed”, then ListAvailable shouldn’t work. But it does work:

Furthermore, after calling Get-Command for the module, the commands in the module are available for general use:

Questions

  1. Is automatic discovery and module auto-loading supposed to be reliable and predictable?
  2. How do I troubleshoot why powershell is sometimes doesn’t find a command until a call to Get-Command -module?
  3. Is it bad practice to rely on powershell to automatically load modules? If so, what is the good practice for automatically loading modules?

Answer:

I can’t speak to whether module auto-loading is intended to be reliable, but I personally do not rely on it in finished code.

If I’m writing a script or module, I always use Import-Module TheModule -ErrorAction Stop, and often use #Requires -Module AciveDirectory,TheModule,SQLPs to ensure that the modules are available.

For interactive use in the PowerShell console or ISE, I do generally rely on auto-loading, but if it fails I just Import-Module manually for the session.

In situations where I always want a specific module loaded for an interactive session, I load it in a profile. To see the various profiles run this (from both ISE and Console):

You can decide where you want to place the code for importing the module based on which user(s) and in which host(s) you want the module to be available.

So far I only do this for posh-git, but it seems like it would fit your use case well.

Source:

Is module auto-loading meant to be reliable? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply