In this week’s post, we will look at the steps needed to create a PowerShell® module containing the functions written in previous posts. While functions are the keystones in code reuse, encompassing them within modules allows the most flexible and easy ways to share code between users and machines.


At its simplest, a PowerShell module can be made by creating a .PSM1 file, which has the same name of your module, and placing your functions within. That file is then itself placed in a folder—again, named after your module.


Function Write-Hello{
     write-host "Hello World"

For example, if I want to create a module called “MyModule,” to share with others, and within that module I want to share with others, I would simply create a folder called “MyModule,” and within that folder a text file called "MyModule.psm1". Next, we simply copy our function(s) into the file.


While modules can be loaded from anywhere, the best practice is to load them in to $home\Documents\WindowsPowerShell\Modules. (If you want to use a non-listed location, simply use the “Import-Module” cmdlet.)


However, you can check a full list of folders by running:


get-item env:psmodulepath | select value -ExpandProperty value


If we do a quick “get-module –listavailable,” we can now see our module is listed.


get-module -listavailable.png


Since it's loaded now into the session, any cmdlets within that module can now be called, simply by calling the relevant command name. We can verify our example by listing all commands that begin with the "write" verb.


get-command -verb write


get-command -verb write.jpg


One point worth noting in the previous examples, is that we can see in the screenshots that the module version is listed as “0.0.” If we want to add metadata to our modules, such as versions, license info, authors, etc., we can achieve this by adding a manifest file (a .psd1 file, which contains a hashtable with all the values). Of course, as with most things PowerShell, there's a cmdlet to help!


get-help New-ModuleManifest


Here is the example I used to build my manifest:


$guid = [guid]::NewGuid()
New-ModuleManifest -path .\MyModule\MyModule.psd1 -Guid $guid -Author 'Michael Halpin' -Description "Demo Module" -ModuleVersion 0.1

These are the basic steps that I used when creating the PowerOrion module. If you have done any work in creating your own modules, feel free to share those in the comments below.