PowerShell Import-Module vs Dot Sourcing

夙愿已清 提交于 2019-12-02 20:16:07

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. :-)

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:

  • If you just use the the functions/scripts in THIS situation(script/job) = use dot source.
  • If you use common functions/script that are used in other scripts too OR you want to call some of the functions interactively etc. = use module.
Roman Kuzmin

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 help Get-Help SomeCommand (this is not true for module help Get-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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!