How-to: Use Modules to distribute PowerShell code.

Functions and scripts can be shared as part of a module to enable easy re-use.

PSModulePath

Each new module should be stored in a sub folder of the \WindowsPowerShell\Modules folder.

By default there are two Modules folders to choose from:

Per system:
%windir%\System32\WindowsPowerShell\v1.0\Modules

Per user:
%UserProfile%\Documents\WindowsPowerShell\Modules

(These locations are defined by the $env:PSModulePath environment variable.)

When testing new modules save them as a 'Per user' module, when deploying to run as a background job move them over to the 'per system' location.

Create a new module

To make a new module, take a normal .ps1 PowerShell script and rename it to have the file extension .psm1 (for PowerShell Module V1).

This script should just contain one or more functions that you wish to make available as a Module.

The folder you save it into should be the same as the name of the module, so if you create snark.psm1 this would be saved as %UserProfile%\Documents\WindowsPowerShell\Modules\snark\snark.psm1

Because the module name and folder name match, the functions within can now be run from the PowerShell command line, you can explicitly load the module with Import-Module snark
In PowerShell 3.0, and above, PowerShell will implicitly import a module the first time any one of the functions or cmdlets in the module is called by a user.

So running one of your functions, like get-snark if that’s the name, will run the function and also load the module.

Once loaded you can use Get-Module and see your module in the list of loaded PowerShell modules. To list the functions now available in the new module, use: Get-Command -Module snark

Module Manifests

Module manifests allow several more advanced features:

A module manifest is named just like the Module itself only with the file extension .psd1
The manifest can be created manually with a text editor or using the New-ModuleManifest cmdlet which will accept (or prompt) for the various details.

“If you have a garden and a library, you have everything you need” ~ Marcus Tullius Cicero

Related PowerShell Cmdlets

Get-Module - Get the modules imported to the session.
Import-Module - Add a module to the session.
New-Module - Create a new dynamic module (only in memory).
Remove-Module - Remove a module from the current session.


 
Copyright © 1999-2024 SS64.com
Some rights reserved