【问题标题】:Add PowerShell function to the parent scope将 PowerShell 函数添加到父作用域
【发布时间】:2011-06-09 18:41:28
【问题描述】:

我在一个文件中有一些 PowerShell 辅助函数。我想让它们在我正在编写的另一个文件的范围内可用,但不会污染全局范围。

Helpers.ps1

function global:Helper1
{
    # this function pollutes the global scope
}
function Helper2
{
    # this function is not visible to the Utility.ps1 file.
}

Utilities.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:驱动器。

任何帮助将不胜感激!

编辑:这是从 Mike 的回答扩展而来的解决方案

Helpers.ps1

function Helper
{
}

Utilities.ps1

&{
    function global:Utility
    {
        . ./Helpers.ps1
        Helper1
    }
}

使用点源语法加载 Helpers.ps1 将其内容置于 Utility 函数的范围内。将 Helpers.ps1 放在 Utility 函数之外会导致它在 &{...} 范围内,但是一旦定义了函数,该范围就会结束。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    您可以在 Utilities.ps1 文件中使用此 sn-p。我们所做的是获取所有当前函数,然后我们对助手进行点源。然后我们对 before 和 after 函数进行比较。我们从 diff 中重新创建全局范围内的函数。

    $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) }"
    }
    

    【讨论】:

      【解决方案2】:

      如果您在函数中对 .ps1 文件进行点源,则 ps1 文件中的定义不是全局的,除非函数本身是点源的。

      【讨论】:

      • 我不知道点源。我是PS新手。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多