2

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

这失败了:

Import-Module Contoso.PowerShell -RequiredVersion "0.0.2"
Import-Module:指定模块“Contoso.PowerShell”,版本为“0.0.2”
未加载,因为在任何模块目录中都找不到有效的模块文件。
在行:1 字符:1
+ 导入模块 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
    目录:C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.1


ModuleType 版本名称 ExportedCommands
---------- -------- ---- ----------------
脚本 0.0.1 Contoso.PowerShell


    目录:C:\Program Files\WindowsPowerShell\Modules\Contoso.PowerShell\Contoso.PowerShell.0.0.2


ModuleType 版本名称 ExportedCommands
---------- -------- ---- ----------------
脚本 0.0.2 Contoso.PowerShell

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

4

1 回答 1

3

之所以Import-Module有效,是因为它使用了不同的参数集;它接受一个或多个[PSModuleInfo]对象,这是Get-Module返回的对象。

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

下一个问题是“为什么不能Import-Module以同样的方式找到版本Get-Module?” 答案是“我不知道”。

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

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

你的结构应该是:

Contoso.PowerShell\0.0.2
Contoso.PowerShell\0.0.3

等等

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.

于 2018-03-05T22:23:19.553 回答