PowerShell 导入模块与点源 [英] PowerShell Import-Module vs Dot Sourcing

查看:60
本文介绍了PowerShell 导入模块与点源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想从我的主要 PowerShell 脚本中分离出我的一些功能,我可以将其编写为 .ps1 文件并点源相同,或者我可以将其创建为 >.psm1 并使用 Import-Module 导入相同的内容.

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.

哪个更好,为什么?

推荐答案

模块最适合图书馆.它们使您可以更好地控制从模块导出的内容.默认情况下,PSM1 文件中的所有脚本变量都是私有的——导入时在模块外部不可见.同样,所有功能都是公开的.但是,您可以在 PSM1 文件中使用 Export-ModuleMember 来精确控制从模块导出的变量、函数、别名、cmdlet 等.模块也可以从您的会话中删除,这是与 .PS1 脚本点源的主要区别.另一个区别是模块函数由它们所在的模块命名,因此您可以通过在模块名称和函数名称前加上\"前缀来轻松访问同名的基于模块的函数,例如PSCX\Get-Uptime.在 ISE 中,此前缀还会调用智能感知支持.

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

这篇关于PowerShell 导入模块与点源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆