Thursday, 20 June 2013

Centrally Stored Modules - Pt. 1 - Module Basics

As i do not come from a developer background, creating power shell modules always seemed like an impossible task.
Every now and then i'd come across scripts which had weird sorts of comments at the top and these strange "Param" and [CmdletBinding()] script blocks which i could never understand.

After all, at that stage my scripts were as simple as initializing a bunch of variables with hard coded values and pass them to New-ADUser command.

Fast forward a couple of years, i'm starting to look for ways to no longer write static scripts and am now looking at ways to package my scripts into something more meaningful.

Say hello to Power Shell Modules. Script Modules in particular.

When i started looking at Power Shell Modules, immediately i thought about having a central place to store them and somehow to set it up so that admins can access these modules with ease.

So what is a Script Module?

A script module is basically a normal .ps1 script which has been renamed to .psm1.

The difference between these 2 files is what you'd normally expect to see inside them.  
While a .ps1 script will be a collection of functions and manipulated code to achieve a specific purpose (for example a script to email an html report), a .psm1 file will generally contain only functions.
There is also a .psd1 file (Module Manifest file) which accompanies the .psm1 file. 

So how do i create one?

Lets say we want to make a module called MyModule.

First thing we would create a folder called MyModule - Folder name is important as this is what Power Shell will read as the name of your Module.

Inside that folder we would create MyModule.psm1 - This is the actual module script file which you will use to store your functions.
Inside the same folder we would create a module Manifest.  Easiest way to do this is to run the New-ModuleManifest commandlet.  Specify the Path as ~path~\MyModule\MyModule.psd1, Fill in as many details as you like. 

 

How does it all work in Power Shell?

There is an environment variable called "PSModulePath".  By default there are 2 locations listed in this variable (C:\Users\*User*\Documents\WindowsPowerShell\Modules and C:\Windows\system32\WindowsPowerShell\v1.0\Modules\).
When you start powershell, powershell checks those folders for a list of modules.  You can then run Get-Module -ListAvailable which will bring up a list of modules which you can import.

to be continued...