如何在 PowerShell 的子文件夹中点源函数

How Do I Dot Source Functions Within a Subfolder in PowerShell

我正在尝试创建一个 PowerShell 模块,它将使用以下代码对在子文件夹 "\Functions" 中找到的任何函数进行点源:

# Get the path to the function files
$functionPath = $PSScriptRoot + "\Functions\"

# Get a list of all the function filenames
$functionList = Get-ChildItem -Path $functionPath -Include *.ps1 -Name

# Loop through all discovered files and dot-source them into memory
ForEach ( $function in $functionList ) {
    . ( $functionPath + $function )
}

如果我将所有函数直接放在“\Functions”文件夹中,这就可以正常工作。然而,这并不理想,因为我认为它不允许在以后正确管理函数文件(尤其是在多个系统管理员可以在任何给定时间修改每个函数的脚本文件的团队环境中)。此外,一些函数从 CSV 或文本文件中获取输入,将这些资产和相应的函数包含在同一文件夹中会更加整洁。

因此我的问题是: 我如何完成我在上面尝试做的事情(即,点源在 中找到的所有函数” \Functions $PSScriptRoot 的子文件夹,即使它们位于子文件夹中?

PS. 最终目标是拥有一个通用模块,我将其分发到我所有的管理工作站,这将使所有管理相关 scripts/functions 我们已经创建了。然后,当我们添加和删除脚本时,每次启动 PowerShell 时,它们都会在模块中动态更新。

这要归功于 Bryan Cafferky YouTube Video 的灵​​感

你可以用一行代码稍微简化一下:

Get-ChildItem -Path "$PSScriptRoot\Functions\" -Filter *.ps1 -Recurse | %{. $_.FullName }

您缺少 -Recurse 参数并且可以使用 $function.FullName 而不是连接 $functionPath$function