简体   繁体   中英

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"

Alternate solution:

function foo {'I am foo!'}

$name = 'foo'

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

I am foo!

You could try the following. It tests if the name specified is a valid function before it attempts to run it:

$myfuncnamevar = "Foo"
Invoke-Command -ScriptBlock {
    param($name)
    if (Test-Path Function:\$name) { 
        #Function exists = run it
        & $name
    }
} -ArgumentList $myfuncnamevar

as simple as :

invoke-expression  $name

or if you want to keep invoke-commande for remoting for example

Invoke-Command -ScriptBlock { invoke-expression  $name}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM