LLI Wiki — My Digital Knowledge Base

Load public and private functions in a PowerShell module

Automatically load the public (exported) and private functions of a PowerShell module from the public and private folders.

A PowerShell module can load its functions automatically when it is imported: the .ps1 files in the public folder are dot-sourced and exported, and those in the private folder are loaded without being exported.

Loading in the .psm1 file

# Load public functions
try {
    $Functions = Get-ChildItem -Path "$PSScriptRoot\public" -Recurse -Include *.ps1 -Exclude *.tests.ps1
    foreach ($function in $Functions)
    {
        . $function.FullName
        $functionName = ($function.Name.Split("."))[0]
        Write-Verbose $functionName -Verbose
        Export-ModuleMember -Function $functionName
        $publicFunctions += $functionName
    }
}
catch {
    Write-Error ("{0}: {1}" -f $function.FullName, $_.Exception.Message)
    exit 1
}


# Load private functions
try {
    $Functions = Get-ChildItem -Path "$PSScriptRoot\private" -Recurse -Include *.ps1 -Exclude *.tests.ps1
    foreach ($function in $Functions)
    {
        . $function.FullName
        $functionName = ($function.Name.Split("."))[0]
        Write-Verbose $functionName -Verbose
        $privateFunctions += $functionName
    }
}
catch {
    Write-Error ("{0}: {1}" -f $function.FullName, $_.Exception.Message)
    exit 1
}

Notes

Mastodon LLIMastodon SocialFosstodon