Search code examples
functionpowershelljobsstart-job

Powershell Start-job invoke function argument with parameter


I have a function mainFunction that gets 2 parameters - $name will be just a regular string, and $moveFunction will be some function.

I want to start a job of a ScriptBlock ($SB) that will invoke $moveFunction with $name as his argument.

function foo($a){
    Write-Output "In function foo with the argument => $a"
}

$SB = { 
        param($C, $fooFunction)
        $fooFunction.Invoke($C)
     } 

function mainFunction($name, $moveFunction){
    Start-Job  -Name "currentJob" -ArgumentList $name, ${Function:$moveFunction} -ScriptBlock $SB

}


$j1 = mainFunction -name "output!" -moveFunction $Function:foo

I checked that $moveFunction exists in mainFunction already ($moveFunction.invoke(5) at mainFunction)

I can't find the problem in passing the function as argument in the start-job.

and from Get-Job -Name "CurrentJob" | Receive-Job I get:

You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : localhost

Any help would be appreciated.

edit: The problem is most likely the way I pass the function as an argument (${Function:$moveFunction}


Solution

  • Just a rehash of my previous comment plus code example. Similar issue here. Essentially, arguments passed to Jobs and Remote commands are serialized. During the de-serialization process, functions and script blocks come out as strings instead of their original type. Fortunately it's a simple process to transform these into invokable scriptblocks using [ScriptBlock]::Create("string").

    function foo {
        write-host "foo"
    }
    
    function bar {
        # This argument comes in as a string
        param($func)
        write-host "bar"
    
        # Create scriptblock from string
        $func = [ScriptBlock]::Create($func)
        $func.invoke()
    }
    
    Start-Job -ArgumentList $Function:Foo -ScriptBlock $Function:Bar
    
    Get-Job | Wait-job
    Get-Job | Receive-job