powershellpowershell-module

What members do I need to add to a PowerShell module manifest file in order to export Cmdlets from multiple files?


Currently, I have a number of *.ps1 Cmdlet files, each providing a different function, e.g.:

Now, I want to convert these into a single module, so I can have their functionality at the ready.

First of all, I guess I will have to edit the above Cmdlet files so they will be providing corresponding Cmdlet functions instead of executing their code immediately.

Next, I would need to add a manifest file (.psd1) to the folder where these files exist.

What would I need to add to the manifest file, so when I write Import-Module Manifest.psd1, all Cmdlet functions will be available to my PowerShell session?


Solution

  • The common solution to this is to load the functions into a nested script module file.

    Create a new script module file (*.psm1), and write a simple dot-sourcing harness, like so:

    $ErrorActionPreference = 'Stop'
    
    $exportedCommands = foreach ($scriptFile in Get-ChildItem $PSScriptRoot -File -Filter *-*.ps1) {
      # dot-source file (loads the function definitions into module scope)
      . $scriptFile.FullName
    
      # output the function name for export
      $scriptFile.BaseName
    }
    
    # Export commands from the nested module
    Export-ModuleMember -Function $exportedCommands
    

    Then in your module manifest, specify:

      RootModule = 'moduleName.psm1'
    

    If the scripts are additional scripts designed to work with a binary module, import the script module as a "nested module" instead:

      NestedModules = @('moduleName.psm1')
    

    In order for auto-discovery of commands to work prior to module import, make sure you also explicitly list the exported functions in the manifest:

      FunctionsToExport = @('Encode-File', 'Decode-File')