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

How do I define RequiredModules in a PowerShell module manifest (psd1)?

我正在尝试在两个 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 的模块清单定义 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.

问题原来是 Test-ModuleManifest 需要在本地系统上安装所有必需的模块。

因此解决方法是安装 Module1,然后验证 Module2 的清单。

https://github.com/PowerShell/PowerShellGet/blob/90c5a3d4c8a2e698d38cfb5ef4b1c44d79180d66/Tests/PSGetPublishModule.Tests.ps1#L1470

您的问题启发了 this GitHub issue建议引入一个选项来 restrict 检查是否模块(在语法上)格式良好,而不是是否可以找到并加载所有引用的模块.

链接的问题主要是关于相关的 bugTest-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