How to run 2 methods simultaneously in PowerShell

3.7k views Asked by At

I've got two functions, each of which I want to run in the background monitoring user behavior. The functions themselves work fine; however, I cannot seem to figure out how to invoke both of them to do work at the same time. In UNIX I would simply use fork() and be done with it, but I am struggling with PS.

#start-job -ScriptBlock $(func1) 
#start-job -ScriptBlock $(func2)

Because the functions each run in an infinite while, the second line is not actually getting called, only the first function is actually doing any work.

I have tried using start-job, invoke-command, start-process, and the start method in [diagnostics.process]. My gut tells me that I am not correctly understanding what start-job does, because if it did run func1 in a background process, then there's no reason this top level script should be blocked. Any help would be appreciated!

2

There are 2 answers

7
Mathias R. Jessen On BEST ANSWER

Use this syntax ${function:Function-Name} to reference the definition of a function:

$job1 = Start-Job -ScriptBlock ${function:func1}
$job2 = Start-Job -ScriptBlock ${function:func2}
0
Ranadip Dutta On

First thing you should use script block to call the function inside.

Secondly, the function has to be declared in the InitializationScript block else Start-job won't understand which function to call.

try something like this:

start-job -InitializationScript {
    #--Define function1 here
    } -ScriptBlock {func1} 

start-job -InitializationScript {
#define your  function2 here
} -ScriptBlock {func2}