Search code examples
powershellpowershell-remoting

Invoke-Command with dynamic function name


I found this awesome post: Using Invoke-Command -ScriptBlock on a function with arguments

I'm trying to make the function call (${function:Foo}) dynamic, as in I want to pass the function name.

I tried this:

$name = "Foo"
Invoke-Command -ScriptBlock ${function:$name}

but that fails. I also tried various escape sequences, but just can't get the function name to be dynamic.


EDIT: For clarity I am adding a small test script. Of course the desired result is to call the ExternalFunction.

Function ExternalFunction()
{
  write-host "I was called externally"
}

Function InternalFunction()
{
    Param ([parameter(Mandatory=$true)][string]$FunctionName)
    #working: Invoke-Command -ScriptBlock ${function:ExternalFunction}
    #not working: Invoke-Command -ScriptBlock ${invoke-expression $FunctionName}
    if (Test-Path Function:\$FunctionName) {
    #working,but how to use it in ScriptBlock?
    }
}

InternalFunction -FunctionName "ExternalFunction"

Solution

  • Alternate solution:

    function foo {'I am foo!'}
    
    $name = 'foo'
    
    $sb = (get-command $name -CommandType Function).ScriptBlock
    invoke-command -scriptblock $sb
    

    I am foo!