PowerShell Module Construction

I’ve created a fair number of PowerShell modules over the last year or so. I’ve experimented with various configurations:

  • multiple functions in a single .psm1 file
  • single function per file all loaded from the .psm1 file
  • modules with and without manifests
  • comment based help in various configurations
  • external help files

I have standardised on the following:

  • single function per file
  • comment based help at the end of the function. Its present but its not intrusive

This is the template I use

function aaaa-yyyyyy{
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true,
   ValueFromPipelineByPropertyName=$true)]
[string]$computer="."
)
BEGIN{}#begin
PROCESS{}#process
END{}#end

<#
.SYNOPSIS


.DESCRIPTION


.PARAMETER  <Parameter-Name>


.EXAMPLE


.INPUTS


.OUTPUTS


.NOTES


.LINK

#>

}

 

I’ve put in the CmdletBinding() so I get an advanced function. I’ve added the parameter statement for pipeline input.

The function body is split into BEGIN/PROCESS/END blocks to make me think about the way the function will work

The keywords for the comment based help are present and the comment block has spaces before and after to ensure other comments don’t conflict.

I keep this as a template to load into ISE.

One thing I might add is the other parameter attributes and the validation functions to save looking them up.

Feel free to amend this suit your needs.

4 Responses to PowerShell Module Construction

  • Personally, I prefer the comment based help at the top as it provides a quick reference point when opening PS1 files.

  • RichardSiddaway says:

    Thats one of the beauties of comment based help – you have the option. I prefer them at the bottom because they are out of the way & I keep my functions very short and very granular

  • JJ says:

    I also put comments at the top for no better reason than I tried it both ways and preferred the top (but I whole-heartedly agree with your comment). However, unless I am writing the help, the comment blocks are always collapsed to keep them out of the way.

  • David English says:

    thanks for this… When starting out I always find a decent working example very useful. Now, my module works the way I was expecting it to :)

Leave a Reply