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?

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,639