PowerShell Modules II
Last time we created a script file with three functions
new-password which controls the creation of a new password
get-randchar which generates a random character from a given character set
add-character which adds one of more characters of a given type to the password using get-randchar
Oops I made the mistake of calling it add-characters in the original script. The convention is that nouns are always singular.
At the moment our three functions are in a .ps1 file that we can dot source to load the functions. This loads all three functions but I only really want new-password to be visible.
An easier way to load functionality is to use the Import-Module cmdlet. First off we need to turn our script into a module. Ok change the name from user.ps1 to user.psm1. Now we can use
Import-Module ./user.psm1
to load the functions. We can see what is loaded by using
PS> Get-Module
ModuleType Name ExportedCommands
---------- ---- ----------------
Script user {add-characters, new-password, get-randchar}
One of the good things about using modules is that Remove-Module will unload the functions. So we’ll do that and have a look at what else might be available with modules
PS> Get-Command *module*
CommandType Name
----------- ----
Cmdlet Export-ModuleMember
Cmdlet Get-Module
Cmdlet Import-Module
Function Load-Modules
Cmdlet New-Module
Cmdlet New-ModuleManifest
Cmdlet Remove-Module
Cmdlet Test-ModuleManifest
Export-ModuleMember looks interesting. It will control the module members such as functions, aliases and variables that are exported by the module – that is they are made available. So we add a last line to the module.
Export-ModuleMember -Function new-password
After importing the module we have
PS> Get-Module
ModuleType Name ExportedCommands
---------- ---- ----------------
Script user new-password
If we do dir function: we will only see our new-password function
By using modules we can control which functions are “published” and which functions remain in the background as invisible worker functions. As we add more functions into our module we just add to the list of functions being exported.
The module can be made even more flexible by creating a module manifest which is the subject of the next post.

Read the complete post at http://richardsiddaway.spaces.live.com/Blog/cns!43CFA46A74CF3E96!2099.entry