何时选择开发 PowerShell 模块而不是 PowerShell 脚本
我即将为 Windows 管理员编写一个 PowerShell 脚本,以帮助他们完成与部署 Web 应用程序相关的某些任务。
我是否有任何理由应该赞成或排除开发 PowerShell 模块 (.psm1),而不是开发 PowerShell 脚本 (.ps1)?
开发脚本的论据
- 简单:我认为使用脚本对于 Windows 管理员来说更容易、更直接,因为它不需要安装模块(但我可能是错误的,因为我不是 Windows 管理员!)。
- 更快的开发:开发模块需要更仔细地编程并暴露内部方法。这就像设计API一样,因此必须更加严格。
开发模块的论据:
- 可重用性:这是首先想到的:如果管理员想将我们的脚本集成到他自己的脚本中,这可能会更容易他重用公开一个(或多个)cmdlet 的模块而不是调用我们的脚本?
- ...
如果您了解 PS 脚本与 PS 模块的常见用例,或者每种选择的技术限制,这可能会有所帮助。
I am about to write a PowerShell Script for Windows administrators, in order to help them in certain tasks related to deployment of a web application.
Is there any reason I should favor or exclude the development of a PowerShell Module (.psm1) instead of doing a PowerShell script (.ps1)?
Arguments to develop a Script
- simplicity: I think that using a script is a bit easier and more straightforward for Windows Administrators as it does not require the module to be installed (but I might be wrong as I am not a Windows Admin!).
- faster development: developing a module requires more careful programming an exposure to internal methods. It is like designing an API an thus must be more rigorous.
Arguments to develop a Module:
- reusability: this is the first thing that comes to mind: if the administrator wants to integrate our script in his own script, it might be easier for him to reuse a module exposing one (or several) cmdlet rather than invoke our script?
- ...
If you know the common use case of PS scripts vs PS modules, or the technical limitations of each choice, it might help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要了解模块可以为您做什么,请阅读以下内容:https://learn.microsoft.com/en-us/powershell/scripting/developer/module/writing-a-windows-powershell-module?view=powershell-7.1< /a>
简而言之,
如果您的脚本已经具有函数并且不仅仅是为了执行单个任务而编写的,您可以将其重命名为 .PSM1 以将其转换为模块。如果您不使用函数,当然,别无选择,只能选择 .ps1。在这种情况下,每个 .ps1 将用于执行单个任务。与他人分享我编写的脚本时,我总是更喜欢模块。
To understand what modules can do for you, read this: https://learn.microsoft.com/en-us/powershell/scripting/developer/module/writing-a-windows-powershell-module?view=powershell-7.1
In a nutshell,
If your script already has functions and is not just written to perform a single task, you can just rename it to .PSM1 to convert it to module. If you are not using functions, of course, there is no choice but to go for .ps1. In such a case, each .ps1 will be used to perform a single task. I always prefer modules when sharing the scripts I write with others.
我喜欢能够“隐藏”函数/变量并仅导出我想要的函数/变量的模块。
I like modules for the ability to "hide" functions/variables and only export the ones that I want.