gpt4 book ai didi

powershell - 在公开 PowerShell 模块成员时,我应该更喜欢 Export-ModuleMember 还是全局范围?

转载 作者:行者123 更新时间:2023-12-05 02:38:25 27 4
gpt4 key购买 nike

我一直在编写一个 Cmdlet,并且为了保持界面整洁,我一直在使用 Export-ModuleMember 手动导出我关心的功能。 .

但是,有人指出我也可以将我的函数直接放在 global: scope 中相反,无需调用 Export-ModuleMember

哪个更好?

# Option A: Export-ModuleMember
function Do-Something {}
Export-ModuleMember -Function Do-Something

# Option B: global scope
function global:Do-AnotherThing {}

# Something else?

谢谢!


我的直觉是 Export-ModuleMember 更好,因为它让调用者决定函数在哪个范围内结束(例如,另一个 cmdlet 可以导入我的 cmdlet 而无需全局公开那些导出的函数),但我我不确定。

免责声明:我在 Microsoft 工作。

最佳答案

你是对的。不正确地导出函数会规避安装模块时通常预期的行为。

例如,Import-Module 可以防止 cmdlet 踩踏当前 session 已经可用的 cmdlet 时的破坏。声明一个具有全局作用域的函数可以规避这一点,并且很少有时候应该这样做,除非模块的目的实际覆盖某些东西(比如它可能设置或修改某些提示方法)。 按照预期执行此操作应该非常清楚谁正在通过模块文档安装模块

Note: Clobbering is the same basic principle of overloading or overriding members in class inheritance. Creating a new entity with the same name that may (overload) or may not (override) have a different signature.

即使 Import-Module 默认情况下在破坏时出错,如果您需要会破坏现有 cmdlet 的 cmdlet,Import-Module -AllowClobber 也是解决方案,并让用户选择是否允许破坏。


但我也不推荐Export-ModuleMember任何一个。相反,您应该使用 list (ModuleName.psd1) 来准备您的模块,并在其中指定导出的函数和 cmdlet。 There are also many other things you can set in the manifest as well .

它的好处是使模块定义在操作上更容易理解。现在您不必用一堆 Export-ModuleMember 命令乱扔代码。

Note: If you don't specify the functions or cmdlets to export in your module manifest, or don't have one and do not make use of Export-ModuleMember, all functions and cmdlets will be exported. This may be desirable or it may not be for a given module, but it's important to understand.


关于编写模块的附加信息

根据评论中的要求,这里有一些关于设计和编写 PowerShell 模块的附加链接:

关于powershell - 在公开 PowerShell 模块成员时,我应该更喜欢 Export-ModuleMember 还是全局范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69588683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com