我在一个文件中有一些 PowerShell 帮助函数。我想让它们在我正在编写的另一个文件的范围内可用,但不会污染全局范围。
Helpers.ps1
function global:Helper1
{
# this function pollutes the global scope
}
function Helper2
{
# this function is not visible to the Utility.ps1 file.
}
实用工具.ps1
&{
./Helpers.ps1
function global:Utility1
{
Helper1
}
function global:Utility2
{
Helper2
}
}
我发现了这个问题:
How do I dynamically create functions that are accessible in a parent scope?但答案讨论了向全局范围添加函数。我真正想要做的是使来自一个 PS1 文件的 Helper 函数可用于调用 PS1 文件,而不用帮助器污染全局范围。
我想避免将函数定义为变量,这可以通过 Set-Variable 和 -Scope 参数实现。我见过的最接近的(来自链接的线程)是在函数中使用 Set-Item:drive。
任何帮助,将不胜感激!
编辑:这是从迈克的回答中扩展的解决方案
Helpers.ps1
function Helper
{
}
实用工具.ps1
&{
function global:Utility
{
. ./Helpers.ps1
Helper1
}
}
使用点源语法加载 Helpers.ps1 将其内容置于 Utility 函数的范围内。将 Helpers.ps1 放在 Utility 函数之外会导致它在 &{...} 范围内,但是一旦定义了函数,该范围就会结束。
最佳答案
您可以在 Utilities.ps1 文件中使用此代码段。我们所做的是获取所有当前函数,然后我们点源帮助器。然后我们对 before 和 after 函数进行比较。我们从差异中重新创建全局范围内的函数。
$beforeFunctions = ls function:
. .\helpers.ps1
$afterFunctions = ls function:
$functionDiff = @(Compare-Object $beforeFunctions $afterFunctions)
foreach($diffEntry in $functionDiff){
$func = $diffEntry.InputObject
invoke-expression "function global:$($func.Name) { $($func.definition) }"
}
关于powershell - 将 PowerShell 函数添加到父作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792746/