Powershell: Don't wait on function return

parallel-processing, powershell

Solution

You can start a method as an asynchronous job, using the `Start-Job` cmdlet.

So, you would do something like this:

function generate_html($var)
{
#snipped
}

Start-Job -ScriptBlock { generate_html team1 }

If you need to monitor if the job is finished, either store the output of Start-Job or use `Get-Job` to get all jobs started in the current session, pulling out the one you want. Once you have that, check the `State` property to see if the value is `Finished`

EDIT: Actually, my mistake, the job will be in another thread, so functions defined or not available (not in a module that powershell knows about) in the thread from which you start your job are not available.

Try declaring your function as a scriptblock:

$generateHtml = { 
    param($var)
    #snipped
}

Start-Job -ScriptBlock $generateHtml -ArgumentList team1
Start-Job -ScriptBlock $generateHtml -ArgumentList team2

Problem

I have a Powershell script where I am invoking a function called generate_html. Is there a way to call the function and not wait on its return before proceeding to the next function call? I would prefer not to have to resort to breaking it out into multiple scripts and running those scripts at same time. ``` function generate_html($var) { ... } generate_html team1 generate_html team2 ```

Original source

Related problems