How Can We Help?
Passing an array to background jobs
One issue you might encounter when using background jobs is how to pass parameters to these jobs. And more specifically arrays.
The issue is that all values on ArgumentList are passed as one array to the code block of the Start-Job cmdlet. The trick is to to present your array as one value to the background job. This can be done through the array notation with (,$myArray).
An example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$job = { param( [PSObject[]]$Array ) $Array | ForEach-Object -Process { $_ } } $arrP = 1..4 | ForEach-Object -Process { New-Object -TypeName PSObject -Property @{ Field1 = $_ Field2 = $_ * 2 } } Start-Job -ScriptBlock $job -ArgumentList (,$arrP) | Wait-Job | Receive-Job -Keep |
If you need to pass multiple arguments, you can add these on the ArgumentList parameter. Like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$job = { param( [string]$String1, [PSObject[]]$Array, [string]$String2 ) $String1 $String2 $Array | ForEach-Object -Process { $_ } } $arrP = 1..4 | ForEach-Object -Process { New-Object -TypeName PSObject -Property @{ Field1 = $_ Field2 = $_ * 2 } } Start-Job -ScriptBlock $job -ArgumentList 'Test1',(,$arrP),'Test2' | Wait-Job | Receive-Job -Keep |
This also works when you need to pass multiple arrays to the background job.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$job = { param( [string]$String1, [PSObject[]]$Array1, [string]$String2, [PSObject[]]$Array2, [string]$String3 ) $String1 $Array1 | %{$_} $String2 $Array2 | %{$_} $String3 } $arr1 = 1..4 | ForEach-Object -Process { New-Object -TypeName PSObject -Property @{ Field1 = $_ Field2 = $_ * 2 } } $arr2 = 1..2| ForEach-Object -Process { New-Object -TypeName PSObject -Property @{ Field3 = $_ Field4 = $_ * 3 } } Start-Job -ScriptBlock $job -ArgumentList 'Test1',(,$arr1),'Test2',(,$arr2),'Test3' | Wait-Job | Receive-Job -Keep |