Creating Script Modules (Part 1): Easy Script Distribution

Suppose you have a few functions that you've written, and you want to be able to distribute those to other folks. For example, recently in class I helped some students write a couple of advanced functions (readthis, this, and this for info on these types of functions) that did some specific things in their environment. They wanted to be able to distribute those functions to other administrators, who would use them as commands from within the shell - not unlike cmdlets.

One option would have been to stuff all those functions into a single script file, and then have the other administrators simply dot-source it:

. scripts/Utilities

Dot-sourcing runs the script without creating a new scope for it, so that the functions end up being defined in the current scope. If they put a command like this into their profile script, then those functions would become available - and look almost exactly like cmdlets - every time they started the shell. 

There's a more formal approach, however, that we decided on in class. By renaming "Utilities.ps1" to "Utilities.psm1," we created a script module. This class decided to modify their computers' PSModulePath environment variable via a Group Policy object, adding the path X:\Admins to the PSModulePath. They they created a directory structure like this:

X:\Admins\Modules\Utilities

Under the Utilities folder, they added Utilities.psm1 - instant script module! Because they added that path to the PSModulePath environment variable, administrators can now import those utilities like this:

Import-Module Utilities

They're a little worried about their function names overlapping with other cmdlets and functions, so making this a script module makes it easy to temporarily remove them: Just use Remove-Module to remove the modules from the shell. 

There are some security interactions: They run their environment in the RemoteSigned execution policy, and this module now qualifies as a remote script, since it's running from a UNC. So they'll be digitally signing it, using a Class 3 code-signing certificate and the Set-AuthenticodeSignature cmdlet. In fact, only one person has the certificate they'll be using, so he acts as a sort of "control point." Nobody can modify the script module without his approval, because they need him to re-sign it after any modifications.

This type of single-file script module is easy to create and work with, but as we started discussing future applications the class realized they needed something a bit more. That'll be the next article!

Interested in more PowerShell articles, FAQs, and tips? Bookmark my PowerShell home page on Windows IT Pro! You can also follow me on Twitter (@concentrateddon) for all the latest in the world of PowerShell. 

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×