Using #PowerShell Dynamic Functions to Initialize a Job

Once in a while you will decide to execute tasks in parallel to speed up the whole process. And you will quickly start exploring PowerShell jobs. Although they are easy to start off, they always spawn a new empty instance of PowerShell. This post provides an example how to work around this.

The following code takes the function body of Get-Verb and passes it as a parameter to Start-Job. Inside the job, a new function (called Test-GetVerb) is created based on the parameter using Invoke-Expression. The output of the new function is displayed by the PowerShell instance which started the job:

$BodyGetVerb = Get-Item -Path Function:\Get-Verb | Select-Object -ExpandProperty ScriptBlock

$job = Start-Job -ScriptBlock {

    "function Test-GetVerb { $($args[0]) }" | Invoke-Expression

} -ArgumentList $BodyGetVerb

$job | Wait-Job | Receive-Job | Format-Table

Instead of using jobs, you should be looking at PowerShell runspaces to parallelize. Boe Prox has written a very helpful module for this called PoshRSJob. He has published a four part series on the Hey, Scripting Guy! blog (part 1, 2, 3 and 4).

If you are interested in exploring the world of PowerShell jobs, checkout my Invoke-Queue cmdlet.

Feedback is always welcome! If you'd like to get in touch with me concerning the contents of this article, please use Twitter.