Exporting Functions in PowerShell Modules

Modules in PowerShell, among other things, will allow code to be shared very easily within a community. One of the issues with scripts and dot sourcing right now is that we end up polluting our working session with a lot of variables and functions that we don't really need. These are helper functions and helper variables that are used by larger functions.

Modules solves this problem. You can create a module (Just name a PS1 script to .PSM1) and specify which functions/variables you want to export.

One way to think about this if you have a C# background is public vs private variables or methods in a class. The exported members are analogous to public methods.

You do this with the export-modulemember cmdlet at the end of your module. Notice that I have four distinct function in my module, test.psm1. However, I am only exporting the functions binn and foo. The other two do not show up when I call get-command. Note that when I call bar, it does indeed have access to foo.

image

BTW, cat2 is an alias I use for Lee Holmes' Syntax Highlighting script. Just wait til you see what else Modules can do, especially Module Manifests. With these we can set all kinds of pre-requisites for our scripts, versions, and a number of other things as well.

Comments are closed