如何动态创建父作用域中可访问的函数?

tel*_*ine 7 powershell scope function dynamic

这是一个例子:

function ChildF()
{
  #Creating new function dynamically
  $DynFEx =
@"
  function DynF()
  {
    "Hello DynF"
  }
"@
  Invoke-Expression $DynFEx
  #Calling in ChildF scope Works
  DynF 
}
ChildF
#Calling in parent scope doesn't. It doesn't exist here
DynF
Run Code Online (Sandbox Code Playgroud)

我想知道你是否能够以这样的方式定义DynF,使其在ChildF之外"可见".

Ste*_*ski 13

另一种选择是使用 Set-Item -Path function:global:ChildFunction -Value {...}

使用Set-Item,您可以将字符串或脚本块传递给函数定义的值.


Sha*_*evy 8

您可以使用global关键字来定义函数的范围:

function global:DynF {...}
Run Code Online (Sandbox Code Playgroud)


Ric*_*erg 7

其他解决方案是对特定问题的更好答案.也就是说,学习创建全局变量的最常用方法是很好的:

# inner scope
Set-Variable -name DynFEx -value 'function DynF() {"Hello DynF"}' -scope global

# somewhere other scope
Invoke-Expression $dynfex
DynF
Run Code Online (Sandbox Code Playgroud)

阅读'help about_Scopes'获取更多信息.