Dot-sourcing module content is useful when a module is being developed, it allows a developer to realize the benefits of having module content split into separate files. It is possible to leave the module as it is, it can be published; many popular modules are. To realize the benefit of a single root module file, the content might be merged. This operation can be performed when testing a module, or when preparing a module for release.
There are a number of modules available that can be used to perform this step. For example, the ModuleBuilder module is capable of merging module content. The ModuleBuilder module requires a build.psd1 file in the root of the module (adjacent to LocalMachine.psd1). The build.psd1 file does not need to contain more than an empty hashtable; it can be used to customize the merge process.
With the file present, the following command may be used to merge the module content:
Install-Module ModuleBuilder -Scope CurrentUser
Build-Module -SourcePath C:WorkspaceLocalMachineLocalMachineLocalMachine.psd1
If the command is run from the same directory as build.psd1, the SourcePath argument can be omitted. For example:
Set-Location C:WorkspaceLocalMachineLocalMachine
Build-Module
The resulting module file is placed in the output folder under the project folder. The output path is configurable. The merge process itself is not very complicated. The following script can be used to achieve a similar result when running from the project root folder (C:WorkspaceLocalMachine):
$configuration = @{
ModuleName = Split-Path $psscriptroot -Leaf
FoldersToMerge = @(
'enum*'
'class*'
'private*'
'public*'
)
FilesToCopy = '*.ps1xml', '*.psd1'
FilesToExclude = 'build.psd1'
}
try {
$ErrorActionPreference = 'SilentlyContinue'
if (Test-Path 'output') {
Remove-Item 'output' -Recurse -Force
}
$outputPath = New-Item 'output' -ItemType Directory
Push-Location (Join-Path $psscriptroot $configuration.ModuleName) -StackName build
Get-ChildItem $configuration.FilesToCopy -Exclude $configuration.FilesToExclude |
Copy-Item -Destination $outputPath -Verbose
Get-ChildItem $configuration.FoldersToMerge -Directory |
Get-ChildItem -Filter *.ps1 -File -Recurse |
Get-Content -Raw |
ForEach-Object {
$_.Trim()
''
} |
Add-Content ('{0}{1}.psm1' -f $outputPath, $configuration.ModuleName)
} finally {
Pop-Location -StackName build
}
As a module grows in complexity, it may be desirable to perform additional tasks during the build step. For example, tests might be run, help files might be regenerated, the module might be published. A more extensive build script might perform these actions.