-1

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? – Sash Oct 21 '16 at 15:48
  • Been digging this issue for last few hours and found really nice work around posted by [Matthew Wetmore] (serverfault.com/users/375609/matthew-wetmore) here 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. – Sash Oct 21 '16 at 20:19
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>
  • 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? – Sash Oct 21 '16 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.