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?
The dot sourcing feature lets you run a script in the current scope instead of in the script scope. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt.
The Import-Module cmdlet adds one or more modules to the current session. Starting in PowerShell 3.0, installed modules are automatically imported to the session when you use any commands or providers in the module. However, you can still use the Import-Module command to import a module.
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With