0

I've been searching this for quite some time and can't seem to get right syntaxes for something that I believe is very useful.

I want to call local function using Invoke-Command, which includes other locally defined functions.

Here's rough example:

Function foo1{
}
Function foo2{
foo1
}
invoke-command -ComputerName SERVERNAME -Credential WHATERVER -ScriptBlock ${Function:foo2}

I got almost everything working except calling function "foo1" from withing "foo2" isn't working out.

What's the correct way to do that?

  • What if you add `return 'This function is called {0}.' -f $MyInvocation.MyCommand` to **both** functions? (Note that I _know_ that `return` keyword is not necessary) – JosefZ Oct 20 '16 at 23:00
  • in my script, "foo2" already has a value that it returns. Just added return 0 to the "foo1". Same issue. Can you elaborate more on the -f $Myinvocation.mycommand? Didn't quite get that part? – ANGRY ADMIN Oct 21 '16 at 15:48
  • Been digging this issue for last few hours and found really nice work around posted by [Matthew Wetmore] (http://serverfault.com/users/375609/matthew-wetmore) [here](http://serverfault.com/a/808953/342617) This allows me to combine all common functions used across remote systems into one file and pass them as a parameter via Invoke-Command and Invoke-Expression It did not completely answer my question how I can do the above, but I think it provided me with a way better way of achieve my goal. – ANGRY ADMIN Oct 21 '16 at 20:19

1 Answers1

0

Your foo1 function is not visible from within foo2 function. It's valid even though foo1 function is declared in global scope (Function Global:foo1).

Use nested functions as follows:

Function foo2 {

    Function foo1 {
        'FOO1: {0} "{1}" :(' -f $MyInvocation.MyCommand.CommandType, 
            $MyInvocation.MyCommand.Name
    }

    foo1

    'FOO2: {0} "{1}" :)' -f $MyInvocation.MyCommand.CommandType, 
        $MyInvocation.MyCommand.Name
}
#foo2              ### debugging output
#"---" 
#foo1              ### would work if delared `Function script:foo1` (or global)
#"---" 
Invoke-Command -ComputerName SERVERNAME -Credential WHATERVER -ScriptBlock ${Function:foo2}

Output proves that foo2's CommandType is script:

PS D:\PShell> D:\PShell\SF\810352.ps1
FOO1: Function "foo1" :(
FOO2: Script "" :)
PS D:\PShell>
JosefZ
  • 1,564
  • 1
  • 10
  • 18
  • Isn't defining one function within another making it only usable within the parent? What if, say, you want to re-use it in another one? – ANGRY ADMIN Oct 21 '16 at 22:55