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.

Published Fri, May 13 2011 20:14 by RichardSiddaway
Filed under: ,

Comments

# re: PowerShell Module Construction

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

Monday, May 16, 2011 6:03 AM by David Stephens

# re: PowerShell Module Construction

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

Monday, May 16, 2011 12:12 PM by RichardSiddaway

# Advanced Function template

In this post I showed my Advanced Function template  msmvps.com/.../archive

Tuesday, May 24, 2011 2:17 AM by Richard Siddaway's Blog

# re: PowerShell Module Construction

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.

Monday, August 08, 2011 10:24 PM by JJ

# re: PowerShell Module Construction

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 :)

Wednesday, December 21, 2011 12:48 AM by David English

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: