Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 815
Dennis G Avatar asked Jan 14 '23 06:01

Dennis G


1 Answers

Alternate solution:

function foo {'I am foo!'}

$name = 'foo'

$sb = (get-command $name -CommandType Function).ScriptBlock
invoke-command -scriptblock $sb

I am foo!

like image 192
mjolinor Avatar answered Feb 01 '23 20:02

mjolinor