Microcode: All About Modules (Windows PowerShell CTP2)

In a previous post, I showed you how you can debug Windows PowerShell cmdlets and providers in Visual Studio and load them up without using installutil.exe.  This very briefly touched on using the command Add-Module, in this case, to load up an assembly containing cmdlets.

This post explains how to use modules, a new feature in Windows PowerShell CTP2.  You must be using at least Windows PowerShell CTP2 or later to use this technology.

From the previous post, you might assume that modules can only be DLLs.  This is not the case.  In fact, modules can either be a single script, a collection of scripts, or a DLL containing cmdlets or providers.  Modules allow you a cleaner way to work with groups of scripts, because they can contain private variables that only those scripts share.  You can also refer to a function within a module, which allows you to group commands more logically and to use more common function names without fear of overwriting the names of other functions.

A previous post already talked about how you can use a DLL as a module ( by simply typing Add-Module DllPath ), so I won't talk about that type of module much more today, except to point out the best advantage I can see:  Now I only write a cmdlet or provider and I do not have to write a snapin.  Perhaps because my fingers are busy enough as it is, I personally believe that shorter code is almost always better, so I think this is a pretty nice step to skip.

Instead of looking at DLLs, I'll look at making modules out of scripts.  I have already introduced a few functions that are good candidates for the two types of modules that I want to use.

The functions are:

These functions are a good case for modules because:

  • Search-WindowsDesktop is generally useful, but is not logically related to Get-RecordedTV.
  • Remove-DVRBySeries and Get-RecordedTV, however, are logically related.  This pair also presents a case where I might only want to surface one of a pair of functions, or both (which is actually very easy, but we'll show that later.

Since Search-WindowsDesktop is the only search related function I've got at the moment, I'm going to put it in a module.  Ready?

  • Open Graphical PowerShell (run gpowershell.exe or All Programs  -> Windows PowerShell (CTP2) -> Graphical Windows PowerShell )
  • Create a new script with CTRL + N (or File->New Script )
  • Copy/Paste Search-WindowsDesktop into Graphical PowerShell
  • Save Search-WindowsDesktop as Search-WindowsDesktop.ps1 in a subdirectory named search under $env:UserProfile\Documents\WindowsPowerShell\packages (CTP2) or $env:UserProfile\Documents\WindowsPowerShell\Modules (post CTP2)
  • Create a file, search.psm1 in the search directory
  • In search .psm1, add this line: .$psScriptRoot\Search-WindowsDesktop.ps1

That's it.

Add an additional line for each other script you'd like to dot source into a module.

Hope this helps,

James Brundage [MSFT]