本文介绍了在父范围内如何动态创建可访问的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子:

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

我想知道你是否可以定义DynF一种在ChildF之外可见的方式。

I was wondering whether you could define DynF in such a way that it is "visible" outside of ChildF.

推荐答案

其他解决方案是具体问题的更好的答案。也就是说,学习创建全局变量的最通用方法是非常好的:

The other solutions are better answers to the specific question. That said, it's good to learn the most general way to create global variables:

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

# somewhere other scope
Invoke-Expression $dynfex
DynF

阅读帮助about_Scopes了解更多信息。

Read 'help about_Scopes' for tons more info.

这篇关于在父范围内如何动态创建可访问的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 06:30