How do I dynamically create functions that are accessible in a parent scope?

怎甘沉沦 提交于 2019-12-19 02:27:20

问题


Here is an example:

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

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


回答1:


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

Read 'help about_Scopes' for tons more info.




回答2:


Another option would be to use the Set-Item -Path function:global:ChildFunction -Value {...}

Using Set-Item, you can pass either a string or a script block to value for the function's definition.




回答3:


You can scope the function with the global keyword:

function global:DynF {...}



回答4:


A more correct and functional way to do this would be to return the function body as a script block and then recompose it.

function ChildF() {
    function DynF() {
        "Hello DynF"
    }
    return ${function:DynF}
}
$DynFEx = ChildF
Invoke-Expression -Command "function DynF { $DynFEx }"
DynF


来源:https://stackoverflow.com/questions/1123634/how-do-i-dynamically-create-functions-that-are-accessible-in-a-parent-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!