Creating a CodePack Module
As I’ve been demonstrating ways to build commands around the APICodePack assemblies, I’ve been forced to hard-code references to load the assemblies. Plus, many functions I’ve created use custom type and formatting extensions. These tools would be much easier to use in a module, so let’s do it.
I’ve written about modules before, and there’s no single best way to structure your module layout. I prefer to organize my module with a specific directory structure. Instead of manually creating the folder structure, here’s a function to do the work for me.
Function New-ModuleLayout {
[CmdletBinding(SupportsShouldProcess)]
Param(
[Parameter(
Position = 0,
Mandatory,
HelpMessage = 'Specify the module name'
)]
[string]$ModuleName,
[ValidateScript({ Test-Path $_ })]
[string]$ParentPath = '.'
)
#sub-folders to create
$subs = 'docs', 'formats', 'types', 'functions', 'assemblies', 'tests',(Get-Culture).Name
Write-Verbose "Creating $ModuleName root directory"
$root = New-Item -Path $ParentPath -Name $ModuleName -ItemType Directory
foreach ($sub in $subs) {
if ($PSCmdlet.ShouldProcess($sub,"Creating sub-folder")) {
New-Item -Path $Root.FullName -Name $sub -ItemType Directory
}
}
#create root module
if ($PSCmdlet.ShouldProcess("$ModuleName.psm1","Creating root module")) {
$rootModule = (Join-Path $root.fullName -ChildPath "$ModuleName.psm1")
$m = @'
Get-ChildItem -path $PSScriptRoot\functions\*.ps1 |
ForEach-Object { . $_.FullName}
'@
$m | Out-File -FilePath $rootModule
}
if ($PSCmdlet.ShouldProcess("$Module.pd1","Creating module manifest")) {
#Add manifest parameters as you need
$paramHash = @{
Path = $rootModule -replace "(?<=\.ps)m1", "d1"
RootModule = "$ModuleName.psm1"
ModuleVersion = '0.0.1'
CompatiblePSEditions = 'Core'
Author = 'Jeff Hicks'
Company = 'JHD Information Technology Solutions, Inc.'
PowerShellVersion = "7.3"
}
New-ModuleManifest @paramHash
}
}
The function will create the top-level module folder, the folder tree, the root module, and the module manifest.
Want to read the full issue?