将 PowerShell 函数添加到父作用域
我的文件中有一些 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
}
}
我发现这个问题: 如何动态创建函数可以在父作用域中访问吗? 但答案讨论了向全局作用域添加函数。我真正想做的是使一个 PS1 文件中的 Helper 函数可用于调用 PS1 文件,不会用助手污染全局范围。
我想避免将函数定义为变量,这可以通过 Set-Variable 和 -Scope 参数来实现。我见过的最接近的(从链接的线程)是在函数中使用 Set-Item:drive.
任何帮助将不胜感激!
编辑:这是从迈克的答案扩展的解决方案
Helpers.ps1
function Helper
{
}
Utilities.ps1
&{
function global:Utility
{
. ./Helpers.ps1
Helper1
}
}
使用点源语法加载 Helpers.ps1 将其内容放在 Utility 函数的范围内。将 Helpers.ps1 放在 Utility 函数之外会导致它位于 &{...} 范围内,但一旦定义了函数,该范围就会结束。
I have some PowerShell helper functions in a file. I'd like to make them available to the scope of another file that I am writing, but not pollute the global scope.
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
}
}
I found this question:
How do I dynamically create functions that are accessible in a parent scope? but the answers discuss adding functions to the global scope. What I really want to do is make the Helper functions from one PS1 file available to a calling PS1 file, without polluting the global scope with the helpers.
I want to avoid defining the functions as variables, which is possible with Set-Variable and the -Scope parameter. The closest I've seen (from the linked thread) is using Set-Item in the function: drive.
Any help would be appreciated!
Edit: here is the solution expanded from Mike's answer
Helpers.ps1
function Helper
{
}
Utilities.ps1
&{
function global:Utility
{
. ./Helpers.ps1
Helper1
}
}
Using the dot-source syntax to load Helpers.ps1 puts it's contents in the scope of the Utility function. Putting Helpers.ps1 outside the Utility function causes it to be in the &{...} scope but that scope ends once the functions are defined.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 Utilities.ps1 文件中使用此代码段。我们所做的是获取所有当前函数,然后我们获取助手。然后我们对之前和之后的函数进行比较。根据 diff,我们在全局范围内重新创建函数。
You can use this snippet in the Utilities.ps1 file. What we do is get all current functions then we dot source the helpers. We then make a diff of the before and after functions. From the diff we recreate the functions in the global scope.
如果您在函数中对 .ps1 文件进行点来源,则 ps1 文件中的定义不是全局的,除非该函数本身是点来源的。
If you dot-source a .ps1 file in a function, the definitions that are in the ps1 file are not global, unless the function was itself dot-sourced.