Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Don't wait on function return

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
like image 378
kernelpanic Avatar asked Feb 10 '14 15:02

kernelpanic


People also ask

How do I use wait command in PowerShell?

In PowerShell, we can use the Start-Sleep cmdlet to suspend/pause/sleep/wait the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to be completed or pausing before repeating an operation.

How do I set timeout in PowerShell?

Output. PS C:\> C:\Temp\TestPS1. ps1 Timeout is for 10 seconds Waiting for 2 seconds, press CTRL+C to quit ... If you enter the Ctrl+C, it will terminate the entire script execution.

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.


1 Answers

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
like image 182
Joseph Alcorn Avatar answered Sep 20 '22 23:09

Joseph Alcorn