Invoking functions from nested modules in a script module do not always trigger a module to autoload

前端 未结 2 948
逝去的感伤
逝去的感伤 2021-02-08 18:37

If I create a manifest module with nested modules, exported functions from all nested modules after the first do not appear in the list of available commands and don\'t trigger

相关标签:
2条回答
  • 2021-02-08 19:11

    I had this line in my .psd1 file

    FunctionsToExport = 'FuncFromMainPsm1 FuncFromSecondPsm1'
    

    which was what I inferred from the line generated by Powershell Tools for Visual Studio:

    # Functions to export from this module
    FunctionsToExport = '*'
    

    This caused my Get-Module -ListAvailable to show what looked like the right thing

    Script     1.0        MyMModule                  FuncFromMainPsm1 FuncFromSecondPsm1
    

    But when I called FuncFromSecondPsm1 I'd get "The term 'FuncFromSecondPsm1' is not recognized...".

    So I changed my export line to

    FunctionsToExport = @('FuncFromMainPsm1', 'FuncFromSecondPsm1')
    

    And now it all works. I can call both functions after my module loads, whether via autoload or Import-Module.

    I have tried this with and without both ModuleList and FileList set. They make no difference.

    0 讨论(0)
  • 2021-02-08 19:18

    Hy Paul, Hy Luken,

    After struggling for a few hours on this topic (with the implicit and declared manifest approach), I opted for the auto generated manifest. In essence, I wrote a ps1 script that generates the manifest, in two steps:

    1. with some 'business' logic, discover what you want to expose
    2. generate the module manifest

    IMHO, Advantage of that approach: I 'fully' understand and master the exposure of the module content.

    below you can find a PS code snippet that follows this approach, hoping it will benefit to other people.

    # module discovery
    $rootModule = "WdCore";
    $modules = Get-ChildItem *.psm1;
    $nestedmodulesNames = $modules | where { $_.BaseName -ne "WdCore"} | % { $_.BaseName } ;
    
    # functions discovery
    $modulesLines = $modules | Get-Content;
    $functionsLines = $modulesLines | where { $_.contains("Function") };
    
    $functionNamePattern = '^Function\s+(?<name>([a-z][0-9|A-Z|-]+))\s?{.*$';
    $functionNames = $functionsLines | where { $_ -match $functionNamePattern } | select { $Matches['name'] } | % { $_.' $Matches[''name''] '};
    
    # generate manifest
    New-ModuleManifest `
        -Path ./WdTools.psd1 -RootModule $rootModule `
        -ModuleVersion '1.0' `
        -NestedModules $nestedmodulesNames `
        -FunctionsToExport $functionNames `
        -Guid '57D7F213-2316-4786-8D8A-3E4B9262B1E5' `
        -Author 'Blaise Braye' `
        -Description 'This module provides working directory tooling' `
        -PowerShellVersion '3.0' -ClrVersion '4.0';
    
    0 讨论(0)
提交回复
热议问题