Refactoring PowerShell Modules into Scripts

on Friday, May 9, 2014

When writing a module the code can pile up pretty quickly. And once you get to a certain point it becomes unwieldy to find function definitions and to “Go to definition” of a method. Especially when you add in Doc Comments.

This can be helped slightly by the PowerShell Tools for Visual Studio. When developing in Visual Studio there is a dropdown of all function names within a file, and they are listed alphabetically. There is also an add-on for the PowerShell ISE, FunctionExplorer, but it is pretty unstable.

One thing that C# developers have done for a while is break out large files into multiple smaller files. Grouping the contents of each file by a specified area. This can also ‘kinda’ be done in PowerShell, and it’s with the help of this trick to get the current script directory.

$root = Split-Path $MyInvocation.MyCommand.Path –Parent

With that function at the top of the module file (.psm1) you can then start adding in normal script files (.ps1) to the module definition. This allows you to break apart a single module into multiple script files.

For example, you could have a Car module:

image

image

And, it can be refactored by the different groupings of functions. Like wheels, doors, or engine.

image

These files can all be loaded by the main Car.psm1 module, using the $root pathing. This will ensure that no matter where the module is imported from, the files that are next to it in the directory get loaded.

image

This also helps separate out unit tests into smaller test groups. Making it easier to debug certain sections of a module. (You may notice that each Test script has the $root variable defined at the top. This is to ensure that each script can have the variable available if it’s run on it’s own.)

image

image

Or debug the entire module at once.

image

0 comments:

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.