6

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
kernelpanic
  • 1,158
  • 5
  • 17
  • 36

2 Answers2

9

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
Joseph Alcorn
  • 2,322
  • 17
  • 23
  • 2
    Note the `-Keep` flag on the receive-job can prevent the automatic deletion of results after receiving. `receive-job -name MyJob -Keep` In case that becomes an issue for any readers. – Knuckle-Dragger Feb 10 '14 at 16:16
  • I get the following error: The term 'generate_html' is not recognized as the name of a cmdlet, function, script file, or operable program. – kernelpanic Feb 10 '14 at 16:33
0

For me, the issue was my function would create a Windows Forms GUI, and stopped the remaining script from running until I closed out the Windows Forms GUI. I found the solution, but for a different command, here: Using Invoke-Command -ScriptBlock on a function with arguments.

Within the -ScriptBlock parameter, use ${function:YOUR_FUNCTION}

function generate_html($var) {
    # code
}

Start-Job -ScriptBlock ${function:generate_html} -ArgumentList "team1"
Start-Job -ScriptBlock ${function:generate_html} -ArgumentList "team2"

Also, if you don't want console output from Start-Job, just pipe it to Out-Null:

Start-Job -ScriptBlock ${function:generate_html} -ArgumentList "team1" | Out-Null
Start-Job -ScriptBlock ${function:generate_html} -ArgumentList "team2" | Out-Null
howdoicode
  • 779
  • 8
  • 16