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

后端 未结 4 693
囚心锁ツ
囚心锁ツ 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: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
    

提交回复
热议问题