If I want to separate out some of my functionality from my main PowerShell script, I can either write that as a .ps1
file and dot source the same or I can create that as a .psm1
and import the same using Import-Module
.
Which one is better and why?
Dotsourcing + script and modules are 2 different things. Modules are great to collect/group functions and cmdlets that you would use in a script. If you have functions that you want to use interactively(you call a function in a console), then module can be a great fit.
If you have one big script that you run to .. let's say "migrate a file share", or a single script that you call regulary using Task Scheduler, then dot-sourcing easier.
It depends on what you need. Summary:
A few module features in addition to other answers.
In PowerShell V3 one does not have to call
Import-Module
in order to use module's exported commands. This is especially useful when commands are used interactively. PowerShell somehow caches and knows all available module commands and even their helpGet-Help SomeCommand
(this is not true for module helpGet-Help about_SomeModule
, though).There are several subtle differences in behavior of dot-sourced functions and script module functions. It is not easy to list them all, here is just one example: Strange behavior with Powershell scriptblock variable scope and modules, any suggestions? Sometimes using script modules gets painful, especially when one discovers unwanted differences and issues too late, i.e. simple things work fine in the beginning of development but complex things start to go wrong later.
All in all, normally I use modules except cases when they do not work well. One of them is invoking user script blocks passed in script module functions.
Modules are best for libraries. They give you more control over what is exported from the module. That is by default all script variables in a PSM1 file are private - not visible outside the module when it's imported. Likewise, all functions are public. However, you can use Export-ModuleMember in your PSM1 file to control exactly what variables, functions, aliases, cmdlets, etc that you export from your module. Modules can also be removed from your session which is a major difference with dotsourcing a .PS1 script. Another difference is that module functions are namespaced by the module they're in so you can easily access identically named module-based functions by prefixing the module name and a "\" to the function name e.g. PSCX\Get-Uptime. In ISE, this prefix also invokes intellisense support.
I generally recommend going with modules. :-)