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

Viewed 6926

I'm trying to create a simple dependency between two PowerShell modules, but I'm getting the syntax or something wrong.

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"
                           }
                         )
}

The module manifest for Module2 defines that Module2 depends on Module1.

When running Test-ModuleManifest Module2.psd1, I get the following error:

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 Answers

Your question inspired this GitHub issue, which proposes introducing an option to restrict checking to whether a module is (syntactically) well-formed, as opposed to whether all modules referenced can be found and loaded.

The linked issue is primarily about a related bug: Test-ModuleManifest currently ignores dependencies on a specific version of a required module - any locally available version passes the test.

As an alternative to your own workaround (installing all required modules locally first), the following approach is a simpler stopgap:

# 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
Related