Import-Module 仅在从 Get-Module 通过管道传输时有效

Import-Module works only when piped from Get-Module

我写了一个简单的 PowerShell 模块。我需要保留更多版本的模块。 版本的所有路径都添加到 $env:PSModulePath 将模块导入我的会话时遇到奇怪的问题。

这失败了:

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

现在奇怪的是 - 存在“0.0.2”版本的模块。我可以成功列出它(Get-Module -ListAvailable)。我什至可以导入它并使用它,但唯一的方法是:

Get-Module Contoso.PowerShell -ListAvailable |
    ? { $_.Version -eq "0.0.2" } |
    Import-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

抱歉造成混淆 - 我在 PSModulePath 环境变量中没有每个版本的路径。

Import-Module之所以有效,是因为它使用了不同的参数集;接受一个或多个 [PSModuleInfo] 对象的地方,即 Get-Module returns.

很可能,它使用 Get-Module 已经完成的工作来确定加载哪个文件。

下一个问题是 "why doesn't Import-Module find the version the same way Get-Module does?",答案是 "I don't know."

虽然它们在任何情况下都应该保持一致,但可能导致麻烦的原因是您的直接结构。您如何存储多个版本?

在我看来你的模块路径不正确。

你的结构应该是:

Contoso.PowerShell[=10=].0.2
Contoso.PowerShell[=10=].0.3

等等

模块文件直接放在版本号文件夹里,不应该在里面另外加名字。

您可以通过使用 Install-Module 从存储库安装一个并查看其处理方式来查看此结构。