问题
I wrote a simple PowerShell module. I need to keep more versions of the module. All paths to versions are added to I'm facing strange problem when importing the module to my session.$env:PSModulePath
.
This fails:
Import-Module Contoso.PowerShell -RequiredVersion "0.0.2"
Import-Module : The specified module 'Contoso.PowerShell' with version '0.0.2' was not loaded because no valid module file was found in any module directory. At line:1 char:1 + Import-Module Contoso.PowerShell -RequiredVersion "0.0.2" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (Contoso.PowerShell:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleWithVersionNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
And now the strange thing - the module with the "0.0.2" version exists. I can successfully list it (with Get-Module -ListAvailable
). I can even import it and work with it, but the only way how to do it is this:
Get-Module Contoso.PowerShell -ListAvailable |
? { $_.Version -eq "0.0.2" } |
Import-Module
Everything works like a charm then. The question is: WHY? I'd like to be able to import the module with the first simple command.
EDIT:
Here is how I store the versions of the module:
Get-Module Contoso.PowerShell -ListAvailable
Directory: C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.1 ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 0.0.1 Contoso.PowerShell Directory: C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.2 ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 0.0.2 Contoso.PowerShell
And sorry for confusion - I do NOT have paths to each version in the PSModulePath environment variable.
回答1:
The reason Import-Module
works is because it uses a different parameter set; one where it accepts one or more [PSModuleInfo]
objects, which are what Get-Module
returns.
Likely, it uses the work already done by Get-Module
to determine which file to load.
The next question then is "why doesn't Import-Module
find the version the same way Get-Module
does?" and the answer to that is "I don't know."
While they should be consistent in any case, a possible cause for trouble is your directly structure. How are you storing multiple versions?
It looks to me like your module paths are incorrect.
Your structure should be:
Contoso.PowerShell\0.0.2
Contoso.PowerShell\0.0.3
etc.
The module files go directly in the version number folder, and it shouldn't additionally have the name inside it.
You can see this structure by using Install-Module
to install one from a repository and taking a look at how it handles it.
来源:https://stackoverflow.com/questions/49120117/import-module-works-only-when-piped-from-get-module