0

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}

sheldonzy
  • 5,505
  • 9
  • 48
  • 86
  • 1
    I did a little poking around and it looks like someone already answered this type of question [here](https://stackoverflow.com/a/11844992/5339918). Essentially, Args for Jobs and Remote commands are Serialized. ScriptBlock comes out the other end as a String. Just call `$func = [ScriptBlock]::Create($func)` to convert that string back into a SB proper and invoke as per normal. – RiverHeart Nov 26 '18 at 01:43
  • @RiverHeart Eventually your comment really helped me. Add your answer I'll approve it =) – sheldonzy Nov 27 '18 at 14:39

2 Answers2

1

You passing the same function and invoking it. You can directly use the function in the job.

Start-Job  -Name "currentJob" -ArgumentList $name - ScriptBlock ${function:foo}
Prasoon Karunan V
  • 2,916
  • 2
  • 12
  • 26
1

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
RiverHeart
  • 549
  • 6
  • 15