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
- The function name is taken from the file name, before the first dot:
Get-Thing.ps1definesGet-Thing. The file must therefore be named after its function. Export-ModuleMemberonly has an effect in a script module (.psm1).- The variables
$publicFunctionsand$privateFunctionsare not initialized in this snippet. Declare them with@()before the loop if you use them afterwards. -VerboseonWrite-Verboseforces the messages to be displayed at every import. Remove it for a silent import.