Contents

How to Build Your First PowerShell Module

11 Sep 2018 0 29  0
How to Build Your First PowerShell Module
How to Build Your First PowerShell Module

 

Are you constantly trying to find that script you know that you wrote months ago but can’t find it? If so, you need to build modules.

If you have multiple PowerShell scripts in a folder somewhere called Scripts, where a bunch of these scripts SQL related, Active Directory, or some private business process; or if you are constantly trying to find a script that you know you wrote a couple of months ago but cannot find it anywhere, this means you need to build modules.

Modules are a feature of PowerShell which allow a scripter to combine many different commands into one ‘package’. This ‘package’ is a single file which contains functionality wrapped around a common theme. After these commands are wrapped up into a module, a scripter can then import that module; this makes every command instantly available in the session. No more messing around for scripts.

At their bare minimum, a PowerShell module consists of a single script which ends with a ‘PSM1’ extension. However, it is recommended that you always include a module manifest too; this is just another PowerShell script which consists of nothing but a hash table of items about the module ending with a file extension of ‘PSD1’. Below is how you can create a module and its corresponding manifest.

How to Create a Module

Every function in a module has some type of common theme. In this tutorial for instance, we will create a module which manages groups of files. Perhaps you have some business reason to create and move around groups of files at once and you have decided to build some functions to make this happen. Those functions have to include New-FileGroup, Remove-FileGroup, and Move-FileGroup. It will look like the below.

function New-FileGroup {
    [CmdletBinding()]
    [Parameter()]
    param(
        [string]$Name
    )
    0..3 | foreach {
        Add-Content -Path "$_-$Name.txt" -Value ''
    }
}

function Remove-FileGroup {
    [CmdletBinding()]
    [Parameter()]
    param( 
       [string]$Name
    )

    0..3 | foreach {
        Remove-Item -Path "$_-$Name.txt"
    }
}

function New-FileGroup {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$Name,

        [Parameter()]
        [string]$NewPath
    )

    0..3 | foreach {
        Add-Content -Path "$_-$Name.txt" -Value ''
    }

 

You can copy paste those functions directly into a PowerShell console and they would work until the session is closed; then you will have to do it again. Instead, simply paste those functions into a ‘PSM1’ text file called ‘FileGroup.psm1′. Then, importantly, make a folder called ‘FileGroup’ in any folder that is displayed when checking the ‘$env:PSModulePath’ variable.

If you want PowerShell to recognize your module, it has to be in one of those folders. For our example, we want our module to be available for every machine on the system, so the PSM1 file will end up being located in ‘C:Program FilesWindowsPowerShellModulesFileGroupFileGroup.psm1’.

You can run Get-Module and see that PowerShell sees your module with all the functions in it.

PS> Get-Module -ListAvailable FileGroup
Directory: C:Program FilesWindowsPowerShellModules

ModuleType      Version      Name                                   ExportedCommands
----------      -------      ----                                   ----------------
Script            0.0        FileGroup                              {New-FileGroup, Remove-FileGroup, Move-FileGroup}

 

Creating a Manifest

You can run every function and it will work, however, you will not know anything else about this module. You will need to add some metadata to it like the author name, organization, description, and others. A manifest will allow you to define what functions are available to the user as well. You will have to build a manifest.

To build a manifest, you can use the built-in ‘New-ModuleManifest’ command. You can create your own but note that a manifest needs to have specific fields and structure and it’ll be easier to use the New-ModuleManifest command to do that.

New-ModuleManifest -Path 'C:Program
FilesWindowsPowerShellModulesFileGroupFileGroup.psd1'
-Author 'Adam Bertram'
-CompanyName 'Adam the Automator, LLC'
-RootModule 'FileGroup.psm1'
-Description 'A module that manages file groups'

New-ModuleManifest then creates a PSD1 file in my module directory. When open in notepad, it will look like this:

#
# Module manifest for module 'FileGroup'
#
# Generated by: Adam Bertram
#
# Generated on: 7/21/2017
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'FileGroup.psm1'

# Version number of this module.ModuleVersion = '1.0'

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = 'a24f61fb-36fb-466f-bfc3-5bcf42565693'

# Author of this module
Author = 'Adam Bertram'

# Company or vendor of this module
CompanyName = 'Adam the Automator, LLC'

# Copyright statement for this module
Copyright = '(c) 2017 Adam Bertram. All rights reserved.'

# Description of the functionality provided by this module
Description = 'A module that manages file groups'

 

There are lots of other keys that can be set here too. When you run Get-Module now, you will be able to see the information being read in the manifest.

PS> Get-Module filegroup | select author,companyname,description

Author                 CompanyName                        Description
-----                  -----------                        -----------
Adam Bertram Adam the Automator, LLC A module that manages file groups

 

0 Comments
Add a comment

Leave a Reply