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

后端 未结 4 695
囚心锁ツ
囚心锁ツ 2021-01-02 11:21

Here is an example:

function ChildF()
{
  #Creating new function dynamically
  $DynFEx =
@\"
  function DynF()
  {
    \"Hello DynF\"
  }
\"@
  Invoke-Expres         


        
相关标签:
4条回答
  • 2021-01-02 12:01

    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.

    0 讨论(0)
  • 2021-01-02 12:09

    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
    
    0 讨论(0)
  • 2021-01-02 12:17

    You can scope the function with the global keyword:

    function global:DynF {...}
    
    0 讨论(0)
  • 2021-01-02 12:23

    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.

    0 讨论(0)
提交回复
热议问题