Creating powershell modules from multiple files, referencing with module

后端 未结 3 671
轻奢々
轻奢々 2021-02-19 16:04

I creating a PowerShell script module using separate source files. What is the canonical way to reference source functions internal to the module from other internal source fil

3条回答
  •  深忆病人
    2021-02-19 16:40

    I've personally followed the practice laid out by RamblingCookieMonster in his blog here: http://ramblingcookiemonster.github.io/Building-A-PowerShell-Module/

    Which is to organise your functions in to separate .ps1 files under sub-folders \Public and \Private. Public contains the functions the user should be able to call directly, Private is the functions internal to PowerShell.

    Then in the .psm1 file you load the functions via a loop and dot sourcing as follows:

    #Get public and private function definition files.
        $Public  = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue )
        $Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue )
    
    #Dot source the files
        Foreach($import in @($Public + $Private))
        {
            Try
            {
                . $import.fullname
            }
            Catch
            {
                Write-Error -Message "Failed to import function $($import.fullname): $_"
            }
        }
    
    # Here I might...
        # Read in or create an initial config file and variable
        # Export Public functions ($Public.BaseName) for WIP modules
        # Set variables visible to the module and its functions only
    
    Export-ModuleMember -Function $Public.Basename
    
    • Source of this example: https://github.com/RamblingCookieMonster/PSStackExchange/blob/db1277453374cb16684b35cf93a8f5c97288c41f/PSStackExchange/PSStackExchange.psm1

    You should then also explicitly list your Public function names in your .psd1 module manifest file under the FunctionsToExport setting. Doing this allows these functions to be discoverable and the module to be auto-loaded when they are used.

提交回复
热议问题