我该如何在PowerShell模块清单(psd1)中定义所需模块(RequiredModules)?

8

我试图创建两个PowerShell模块之间的简单依赖关系,但是我在语法或其他方面出了问题。

Module1.psd1

@{
    RootModule        = 'Module1.psm1'
    ModuleVersion     = '1.0'
    GUID              = '11111111-1111-1111-1111-111111111111'
    Author            = 'uw'
    FunctionsToExport = @()
    CmdletsToExport   = @()
    VariablesToExport = '*'
    AliasesToExport   = @()
}

Module2.psd1:

@{
    RootModule        = 'Module2.psm1'
    ModuleVersion     = '1.0'
    GUID              = '22222222-2222-2222-2222-222222222222'
    Author            = 'uw'
    FunctionsToExport = @()
    CmdletsToExport   = @()
    VariablesToExport = '*'
    AliasesToExport   = @()
    RequiredModules   = @(
                          @{
                            ModuleName = "Module1"; 
                            ModuleVersion = "1.0"; 
                            Guid = "11111111-1111-1111-1111-111111111111"
                           }
                         )
}

Module2的模块清单定义了依赖于Module1

运行Test-ModuleManifest Module2.psd1时,我遇到以下错误:

Test-ModuleManifest : The specified RequiredModules entry 'Module1' in the module manifest 'Module2.psd1' is invalid. 
Try again after updating this entry with valid values.
2个回答

10

4
你的问题启发了 此 GitHub 问题,该问题建议引入一个选项来 限制 检查一个模块是否(在语法上)格式良好,而不是检查是否可以找到和加载所有引用的模块。

链接的问题主要涉及相关的错误:当前 Test-ModuleManifest 忽略对所需模块的特定版本的依赖关系 - 任何本地可用版本都可以通过测试。

作为自己的解决方法(先在本地安装所有所需的模块)的替代方案,以下方法是一种更简单的权宜之计:

# Run Test-ModuleManifest and collect any errors in variable $errs while
# suppressing immediate error output.
Test-ModuleManifest ./Module1.psd1 -ErrorVariable errs 2>$null

# Remove the errors relating to the 'RequiredModules' key, which we want to ignore.
$errs = $errs | ? { $_.ToString() -notmatch '\bRequiredModules\b' }

# Output any remaining errors.
$errs | % { Write-Error -ErrorRecord $_ }

# Determine success:
# Testing the manifest succeeded, if no errors other than the anticipated
# one relating to 'RequiredModules' occurred.
$ok = $errs.Count -eq 0

1
PowerShell 5.1仍存在一个错误,为网络共享上的模块创建清单,其中所需的模块也在默认的PowerShell/Modules路径中。如果删除这些本地模块,则即使所需的模块位于网络共享中,也无法更新清单。 - kevinskio
1
@kevinsky:鉴于Windows PowerShell将不会有新的开发,只会进行关键性错误修复,我怀疑它在那里是否能被修复。我预计它将在某个时候被在PowerShell Core中修复,但目前尚不清楚何时会发生(肯定不会在即将到来的v7.0版本中)。 - mklement0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接