PowerShell modules are another way to implement reusability in your scripting. A PowerShell module is more extensive than a function because it can contain multiple items like functions, variables, providers, workflows, and so on. Modules can also persist on a disk, and can be referenced or imported by other scripts.
There are four types of modules as of PowerShell V4:
A binary module is based on a dynamic linked library (dll) file.
A manifest module is a module that includes a manifest, which describes what a module contains and how it is processed (visit http://msdn.microsoft.com/en-us/library/dd878337(v=vs.85).aspx).
A dynamic module is one that is not persisted to a disk. These can be created using the
New-Module
cmdlet.
In this appendix, we are only going to focus on script modules. However, if you are interested in creating the other types of modules, you can refer to http://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx.
As I just mentioned, one type of module we can create is called script module. This allows you to create modules purely from your PowerShell script code – either an existing one, or one you're about to write.
The steps to create script modules are as follows:
Save your
.ps1
file to.psm1
.Optionally, create a folder in one of the standard modules folder. This has to have the same name as your module file.
Import the module.
Modules, by default, are saved in a few default folders. To see these folders, you can use the environment variable $env:PSModulePath
. This returns a semicolon-delimited string. To see each directory in its own line, you can use the split method:
($env:PSModulePath -split ";")
The following screenshot shows the result I got in my environment:
Here is a simple illustration of how you can convert your script files into a module. Assume we have a file called Custom.ps1
that contains some PowerShell scripts. Usually, we run this file before we can use the functions inside it. To convert this into a script module, take the following steps:
Rename the
Custom.ps1
file toCustom.psm1
.Create a folder called
Custom
in one of the standard module folders. Let's chooseC:\Windows\system32\WindowsPowerShell\v1.0\Modules
.Save the
Custom.psm1
file in theCustom
folder:Open your PowerShell console or ISE and import the module using the
Import-Module
cmdlet. Recall though that starting from PowerShell V3, module autoloading is supported, meaning that you don't have to explicitly import the module. Once you use the functions in that module, the module is essentially imported (as long as the module is stored in one of the standard folders):In the preceding screenshot, the
-Verbose
switch was used to show that the.psm1
file was imported from theCustom
folder.