powershellarraylistworkflowparallel.foreachinline-scripting

add an item to arraylist in powershell workflow foreach -parallel


How can we add an item to an arraylist while using foreach -parallel loop in powershell workflows?

workflow foreachpsptest { 
  param([string[]]$list)
  $newList = [System.Collections.ArrayList]@()
  foreach –parallel ($item in $list){
    $num = Get-Random 
    InlineScript {
      ($USING:newList).add("$num---$item")
    }
  }
  Write-Output -InputObject "randomly created new List: $newList"
} 
$list = @("asd","zxc","qwe","cnsn")
foreachpsptest -list $list

Solution

  • The problem here is that you're using, uh $using: the wrong way.

    Your workflow is basically it's own sandbox. You can use $using to instantiate a variable with the same values within it, but you can't use that to manipulate the same variable outside of it.

    However, you can have your workflow emit an object, and then capture that with the .Add() method of your $newlist Arraylist variable.

    Tweak the code like so, and it should work:

    #Moved the Arraylist declaration outside
    $newList = [System.Collections.ArrayList]@()
    
    workflow foreachpsptest { 
    param([string[]]$list)
    foreach –parallel ($item in $list){
          $num = Get-Random 
          InlineScript {
          #use the using: context to pass along values, then emit the current object
          "$using:num---$using:item"
          }
    }
    } 
    
    $list = @("asd","zxc","qwe","cnsn")
    #kick off the workflow and capture results in our arraylist
    $newList.add((foreachpsptest -list $list))
    

    Then, after the code has run, we can get the values out, like so.

    $newList
    58665978---qwe
    173370163---zxc
    1332423298---cnsn
    533382950---asd