I'm a novice in PowerShell. I have encountered a problem with importing modules. It seems that an installed module will be automatically imported when I try to invoke a cmdlet in this module.
That's is:
Install-Module -Name PSscriptAnalyzer
Get-Module PSScriptAnalyzer
# Show nothing
PSScriptAnalyzer
:
Invoke-ScriptAnalyzer -Path ./ -Recurse
# Ignore any info
PSScriptAnalyzer
will be automatically imported:
Get-Module PSScriptAnalyzer
It shows as the follows:
ModuleType Version PreRelease Name
ExportedCommands
---------- ------- ---------- ---- ----------------
Script 1.21.0 PSScriptAnalyzer {Get-ScriptAnalyzerRule, Invoke-Formatter, Invoke-ScriptAnalyzer}
Why will the module be imported automatically as long as its ExportedCommands
have been imported? What is the mechanism it is?
And if so, the Remove-Module
doesn't seem to make much sense in general usage scenarios anymore.
Thanks in advance.
This is feature is called Module Auto-Loading and it was introduced in PowerShell 3.0:
PowerShell imports modules automatically the first time that you run any command in an installed module. You can now use the commands in a module without any set-up or profile configuration, so there's no need to manage modules after you install them on your computer.
And if so, the
Remove-Module
doesn't seem to make much sense in general usage scenarios anymore.
It is true that the cmdlet is rarely used however, Remove-Module
still has its purpose, mainly for module development. The cmdlet is still viable when you need to test changes to your module without needing to restart the session (this is only true for non-binary modules, for binary modules you must restart the session, assemblies cannot be unloaded). Import-Module -Force
also works for the same use case.
Another use case, also a rare one, is for modules that have a custom OnRemove
callback. See Using the OnRemove event.