Archive

Archive for March, 2014

Call PowerShell Script Function from a Job

March 13, 2014 Leave a comment

One of the blockers which I’ve had previously in writing concurrent PowerShell scripts is the fact that any new PowerShell job runs in a new PowerShell.exe instance and has no idea about your script. Since it doesn’t know about your script, any references to any script functions can’t be ran in the job. But I have figured out a way.

The following script is one where a new PowerShell job is started, and that job calls on a function from the script. The trick is to dot load the script before calling the function, and have a line in the script which returns if it is being ran because it was dot sourced.

function MyFunc
 {
 param($message)
$tid = [Threading.Thread]::CurrentThread.ManagedThreadId
 Write-Host "$message on $PID $tid"
 "Return value from process $PID thread $tid"
 }
if($MyInvocation.InvocationName -eq '.') { return; }
$def = $MyInvocation.MyCommand.Definition
Write-Host $def
$Jobs = @();
 $data = @();
 $names = @( "John", "George", "Mary" )
 foreach($name in $names){
 $Jobs += Start-Job -ScriptBlock { param($scriptToDotSource, $toPassAlong) . $scriptToDotSource; MyFunc $toPassAlong } -ArgumentList $def, $name
 }
foreach($job in $jobs){
 $returned = Receive-Job $job -Wait
 $data += $returned
 }
Write-Host "Break"
$data