Monthly Archive

Categories

Module Structure

Since PowerShell 2.0 appeared I have been steadily converting a lot of scripts to modules. Up until now I have been using a single .psm1 file (and possibly a .psd1 file for the manifest).  The .psm1 file contains all of the functions.  Some of my .psm1 files are getting a bit unwieldy so I decided to split them up using the modules in the Windows 7 PowerShell pack as an example.

In the pack each module folder has a set of .ps1 files – one function per file.  The .psm1 file then dot sources the .ps1 files.  That seemed about what I wanted but I wanted to cut the number of files.

What I ended up with was something like this – using my filefunctions module as an example

FileFunctions.ps1
FileFunctions.psd1
FileFunctions.psm1
FolderFunctions.ps1
RecycleBinFunctions.ps1
ShareFunctions.ps1
TempFunctions.ps1
Trinet.Core.IO.Ntfs.dll
XmlFunctions.ps1

The .psd1 file loads the DLL (used for working with Alternate Data Streams) and calls the .psm1 file.  There are a number of helper functions in this module that I don’t want to expose.  I originally controlled this in the .psd1 file

The .psm1 file looks like this

. $psScriptRoot\FileFunctions.ps1
. $psScriptRoot\FolderFunctions.ps1
. $psScriptRoot\RecycleBinFunctions.ps1
. $psScriptRoot\ShareFunctions.ps1
. $psScriptRoot\TempFunctions.ps1
. $psScriptRoot\XmlFunctions.ps1

 

where $psScriptRoot contains the directory from which the module is executed. Useful if you move the location of your modules.

I use Export-ModuleMember in each .ps1 file to control which functions are exposed.

So far it seems to work and does the job.  I’m trying it on few modules before converting to this as a standard but it seems to give me the best of flexibility, control and keeping the code manageable.

Technorati Tags: PowerShell,module structure

Leave a Reply