title: Powershell - foreach to array as job (local / multi-threaded)
body: <p>I'm trying to parse a site to collect price and product details. The script works in a loop however it's very slow. So I'm trying to run a multi-threaded powershell script as a job. </p>
  
  <p>I've tried a lot of suggestions but I'm struggling to get the results out even though I can see its working (the web-request screen flashing up)</p>
  
  <p>I'm only selecting the last 10 but I'll put in a throttle later. Just can't get it to output. Essentially I'd like all results to flow back into $arr. </p>
  
  <hr>
  
  <pre><code>#Import Danmurphy Sitelist
  [xml] $XmlDocument = (New-Object System.Net.WebClient).DownloadString("http://www.example.com/sites.xml")
  
  #get websites listed
  $ImportedProducts = $XmlDocument.DocumentElement.url | select -Last 10
  
  "Killing existing jobs . . ."
  Get-Job | Remove-Job -Force
  "Done."
  
  #loop through the products
  
  #Create Array
  $arr = @()
  
  #$argumentlist 
  
  #ScriptBlock
  $ScriptBlock = {
  Param($product,$arr)
  
  if ($product.loc -like "http://www.example.com/product/*"){
  
  $uri = $product.loc
  $WebResponse = Invoke-WebRequest -Uri $uri -SessionVariable WS 
  
  
  #mainpricetest
  $mainprice = $WebResponse.AllElements | ? { $_.Class -eq 'price-main' } | select innerText
  
  $MainPriceArray = $mainprice.innerText.Split(' ')
  
  $MainUnitArry = $MainPriceArray[1..10]
  
  $MainDollar = $MainPriceArray[0]
  
  $MainUnit = $MainUnitArry -join ' '
  
  
  $item = New-Object PSObject
  $item | Add-Member -type NoteProperty -Name 'Product Site' -Value $($product.loc)
  $item | Add-Member -type NoteProperty -Name 'Main Price' -Value $($MainDollar)
  $item | Add-Member -type NoteProperty -Name 'Main Unit' -Value $($MainUnit)
  
  
  
  $arr += $item
  
  }
  }
  
  foreach ($product in $ImportedProducts){
  Start-Job -InputObject $ImportedProducts -ScriptBlock $ScriptBlock -ArgumentList $product,$arr
  }
  
  $data = Get-Job * | Receive-Job 
  
  #Show Array
  $arr
  </code></pre>