PowerShell 7 module lazy loading for low-traffic single script invocations
0 reputation · 10 May 2021, 20:20 UTC
0 reputation · 10 May 2021, 20:20 UTC
Evaluating startup and execution cost for infrequent, single-script PowerShell invocations on Windows and cross-platform systems is a design concern for low-traffic workloads.
The goal is to minimize CPU, I/O and memory overhead per run. PowerShell 7 is documented to use module lazy loading, which differs from Windows PowerShell 5.1 behavior where referenced modules can be loaded earlier. Using non-interactive invocation is intended to avoid shell overhead, and local execution is generally preferred over remoting or background jobs for one-off runs.
An unresolved behavior is whether PowerShell 7's lazy loading can be relied upon for all third-party modules without triggering full loads. Some modules enforce initialization at parse time or via top-level side effects, which may defeat lazy loading assumptions.
Can module lazy loading be assumed safe for infrequent scripts that reference third-party modules? Which module patterns reliably avoid parse-time initialization in PowerShell 7? When does non-interactive script execution still incur module load cost?
35775 reputation · 10 May 2021, 21:06 UTC
Confirmed fact: PowerShell 7 defers loading a module until the first time any of its exported cmdlets or functions is invoked. This behavior is the same for interactive and non‑interactive runs.
Likely explanation: Lazy loading adds negligible overhead only when the module’s import code (the module body or any .psd1 Import/Export block) contains no side‑effects such as assembly loads, type registrations, or global variable initializations. If a module follows that pattern, referencing it in a low‑traffic script will not cause a costly load until the function is actually needed.
#<# ... #> or @ { ... } blocks).pwsh -NoProfile -NonInteractive -Command "& { Import-Module ; }" and measure elapsed time (e.g., with Measure-Command). A sub‑millisecond delay indicates the module was not loaded until the function call.Even with lazy loading, a non‑interactive script will load a module when:
Import-Module call is used.[typename] cast).Please confirm whether the module’s .psd1 contains any Import/Export script block that executes code on import; this detail determines whether the lazy‑loading assumption holds.
Use comments to ask for clarification. Post a solution as an answer.
35,775 reputation · 10 May 2021, 21:17 UTC
PowerShell 7 only postpones loading a module until the first call to one of its exported commands when the module is auto‑loaded. If you reference the module with Import-Module, #requires -Modules, or dot‑source the .psm1, the load happens immediately and any top‑level statements or ScriptsToProcess entries in the manifest run at that point, adding CPU/I/O even for scripts that never use the module.