因此,我用一堆.ps1
文件(每个函数一个)和.psd1
清单文件实现了我的第一个Powershell模块。
我正在努力理解.psm1
文件的用途--在我的模块中需要它们吗?
它们的附加值是多少?
编辑1
这是我的.psd1
文件:
@{
ModuleVersion = "0.0.19106.59054"
GUID = "59bc8fa6-b480-4226-9bcc-ec243102f3cc"
Author = "..."
CompanyName = "..."
Copyright = "..."
Description = "..."
ScriptsToProcess = "vsts\config.ps1"
VariablesToExport = @(
"TfsInstanceUrl",
"TfsApiVersion",
"QANuGetRepoUrl"
)
NestedModules = @(
"db\Backup-Database.ps1",
...
"vsts\work\Get-WorkItems.ps1"
)
FunctionsToExport = @(
"Assert-ExtractionDestFolder",
...
"Write-HostIfNotVerbose"
)
PrivateData = @{
PSData = @{
ExternalModuleDependencies = "SqlServer"
}
}
}
就像我说的,每个函数都在自己的文件中。
发布于 2019-04-27 16:15:54
.psm1
文件的目的是什么?在我的模块中需要它们吗?
*.ps1
文件提供了与常规的*.ps1
脚本文件不同的特定于模块的行为(单独的、隔离的范围、私有命令、对导出命令的控制)。- Typically, a script module manifest has a `RootModule` entry pointing to (the main) `*.psm1` file; for smaller modules it is not uncommon for _all_ of the module's functionality to be implemented in this one `*.psm1` file.
- In fact, a _stand-alone_ `*.psm1` file can also act as a module, though it doesn't integrate with PowerShell's module auto-discovery and auto-loading feature.
- Note that if you were to use a regular `*.ps1` script directly in `RootModule`, its definitions would be loaded into the _caller's_ scope, not the module's; that is, you would lose the benefits of a module.
*.ps1
NestedModules
清单条目中列出常规的脚本,但由于使用了该特定条目,这些脚本是在 module's上下文中点源的,从而成为模块的一部分。- This is conceptually equivalent to creating and referencing a root `*.psm1` script in `RootModule`, and - instead of defining a `NestedModules` entry - explicitly dot-sourcing your `*.ps1` scripts from _there_ - see bottom section.
- Note that if you were to reference `*.psm1` files in `NestedModules`, they would truly become _nested modules_, with their own scopes; a nested module is usable from the enclosing module, but not visible to the outside world (though you can _list_ it among the loaded modules with `Get-Module -All`).
列出*.ps1
文件中的NesteModules
和从RootModule
中获取的点源
虽然功能应该没有区别,但是使用*.psm1
RootModule
来点源包含模块功能的*.ps1
文件可能会简化一些事情,如果您只需要点源位于模块目录子树中的所有*.ps1
文件:
# Add this to the *.psm1 file specified in 'RootModule'
# Find all *.ps1 files in the module's subtree and dot-source them
foreach ($script in
(Get-ChildItem -File -Recurse -LiteralPath $PSScriptRoot -Filter *.ps1)
) {
. $script
}
如果您需要按特定顺序加载脚本,只需要脚本的一个子集,或者希望稍微加快速度(尽管我怀疑速度差异是否明显),您可以从RootModule
*.psm1
文件中单独创建文件,以替代在NestedModules
条目中列出它们:
# Add this to the *.psm1 file specified in 'RootModule'
# Dot-source the *.ps1 files individually.
. "$PSScriptRoot/db/Backup-Database.ps1"
# ...
. "$PSScriptRoot/vsts/work/Get-WorkItems.ps1"
同样,上述所有方法在功能上都是等价的。考虑到您通过ExportedFunctions
条目显式导出函数(这是可取的),使用必须是点源的*.ps1
文件最终是一个实现细节,与命令发现和模块自动加载的目的无关--只有在实际导入时才重要。
https://stackoverflow.com/questions/55876838
复制相似问题