Written by 8:00 am Microsoft, PowerShell, Windows Server

How to create a Powershell v2 Module

Powershell Header

If you need some functions a lot in different scripts you create maybe external function files. This is a good way to clean up your code. To get this functions running in your mainscript.ps1 you can call this other file “dotsourced”:

. C:\PSscript\output\sayhello.ps1

If you have more than one external function you have to call each file:

. C:\PSscript\Modules\Output\sayhello.ps1
. C:\PSscript\Modules\Output\saygoodday.ps1
. C:\PSscript\Modules\Output\saybye.ps1

In Powershell v2 you can create your own modules, which you can call by:

Import-Module C:\PSscript\Modules\Output

Now how can you create this output module?

  • First you create a directory for the all modules, called Modules
  • Secound you create a directory for the Output module, called Output
  • Than copy all of your Powershell Scripts (.ps1 files) in to this folder
  • Now create a file called Output.psm1. Its important that this file has the same name as the folder
  • In this file write the following code (for each file in this folder):
    . ./Modules/Output/sayhello.ps1
    . ./Modules//Output/saygoodday.ps1
    . ./Modules//Output/saybye.ps1

Now you can use the Import-Module to import your own module called output.

There are a lot of other things you can use to make everything a little bit easier, like system variables for the module and script paths.

Tags: , , , , , , , , , Last modified: July 5, 2019
Close Search Window