在 PowerShell 3 及更高版本中,RequiredModulesare自动加载
这也是确保人们使用 PowerShellGet(即PowerShell 画廊)如果您要分发该模块,请安装您的依赖项。
如果缺少所需的模块,它仍然会失败,但否则会完全按照您希望的方式工作。
在PowerShell 2中,无法自动加载RequiredModules
在任何一种情况下,用户都可以通过键入手动加载需求Import-Module RequiredModule, YourModule
-- 如果已经导入,他们将不会获得第二个实例......
您还可以在 NestedModules 中指定模块。即使在 PowerShell 2 中,这些也会加载到模块“内部”,但不会seem当资源已经加载时会对资源产生负面影响。然而,正如@JasonMArcher提醒我的那样,在PowerShell 2中,如果您的模块被卸载(通过Remove-Module),NestedModules会与您的模块一起卸载,并且会发生这种情况即使它们是单独预加载的由用户创建,这最终可能会产生非常奇怪的错误报告,因为您的用户不会想到这一点。
另一种选择,适用于所有版本的 PowerShell, 是调用Import-Module
在模块的顶部(在 psm1 脚本中,检查确保模块尚未加载后)-ErrorAction Stop
设置为,如果依赖模块的导入失败,则您的模块的导入也会失败。
if (!(Get-Module Dependency)) { ## Or check for the cmdlets you need
## Load it nested, and we'll automatically remove it during clean up
Import-Module Dependency -ErrorAction Stop
}
实际上,如果您想检查版本......
if (!(Get-Module Dependency | Where { $_.Version -ge "2.5" )) {
## Load version 2.5 (or newer), or die
Import-Module Dependency -Version 2.5 -ErrorAction Stop
}
请记住,这并不作为文档,因此如果您分发该模块,您的用户将不知道依赖项。