PowerShell ScriptBlock and multiple functions

Knows Not Much picture Knows Not Much · Oct 27, 2012 · Viewed 11k times · Source

I have written the following code:

cls
function GetFoo() { 
    function GetBar() {
        $bar = "bar"
        $bar
    }

    $foo = "foo"
    $bar = GetBar
    $foo
    $bar
}


$cred = Get-Credential "firmwide\srabhi_adm"
$result = Invoke-Command -Credential $cred -ComputerName localhost 
-ScriptBlock ${function:GetFoo}
Write-Host $result[0]
Write-Host $result[1]

It works but I don't want to define GetBar inside of GetFoo.

Can I do something like this?

cls
function GetBar() {
    $bar = "bar"
    $bar
}

function GetFoo() {     
    $foo = "foo"
    $bar = GetBar
    $foo
    $bar
}


$cred = Get-Credential "firmwide\srabhi_adm"
$result = Invoke-Command -Credential $cred -ComputerName localhost 
-ScriptBlock ${function:GetFoo; function:GetBar; call GetFoo}
Write-Host $result[0]
Write-Host $result[1]

Basically I am selectively putting the functions which I want in the ScriptBlock and then calling one of them. This way I don't have to define function inside of function and I can construct the ScriptBlock by injecting the functions which I want to be a part of that ScriptBlock.

Answer

Andrey Marchuk picture Andrey Marchuk · Oct 29, 2012

The problem is that Invoke-Command can only see what's inside ScriptBlock, it can't see functions definded outside. If you really want to - you can run everything in one line, like this:

$result = Invoke-Command  -ComputerName localhost  -ScriptBlock { function GetBar() { $bar = "bar"; $bar }; function GetFoo() { $foo = "foo"; $bar = GetBar; $foo;  $bar }; GetFoo }

But I personally would advise you to save functions in script and call Invoke-Command with -FilePath parameter, like this:

$result = Invoke-Command  -ComputerName localhost  -FilePath "\1.ps1"