4

I am trying to figure out the best way to organize a Powershell module on disk.

I think it is wise to put each cmdlet in its own file, but if I do that it seems that I am still required to dot source them in the psm1 file, even if I have listed the file in the module manifest. Is there any way around having to include these scripts in the psm1 file? If not, what is the point of the module manifest? I feel like all that information could just be contained in the psm1 file.

1 Answer 1

4

Typical practice is to organise your functions in to individual files under private and public folders. Public are ones your users will call, private are internal to the script. Then you can use a loop to load them all, as well as use the module manifest to expose the public ones:

$Public = @( Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" ) $Private = @( Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" )

@($Public + $Private) | ForEach-Object {
    Try {
        . $_.FullName
    } Catch {
        Write-Error -Message "Failed to import function $($_.FullName): $_"
    } }

Export-ModuleMember -Function $Public.BaseName Export-ModuleMember
-Variable 'LogPath'

Example:

https://github.com/markwragg/Powershell-SlackBot/tree/master/SlackBot

The module manifest is still worthwhile, it delivers other benefits like allowing cmdlets to be discoverable even if the module isn't loaded and declaring dependencies (such as format xml files, or other modules that this module depends on). It's also a requirement of publishing the module in to the Powershell Gallery.

Sign up to request clarification or add additional context in comments.

4 Comments

You can also create one large module and choose which functions to export. See this link for additional information.
@user4317867, that is what I am trying to avoid. I think most people would agree the files representing individual functions is better than keeping everything in one. It's easier to maintain.
@Mark, I think I am doing something similar. I accomplish this by naming private methods without '-' in the name and then just call Export-ModuleMember -Function -. That would have the same result, yes?
Yes, but I think you still need to explicitly name the public ones in the functionstoexport field of the manifest to all autodiscovery of them (without the module being explicitly loaded).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.