Creating objects parallel in powershell workflow and adding it to an array

4.9k views Asked by At

I need to create many objects in parallel inside a workflow and add all of the objects to an array. My code would be something like this

workflow sample {
    $ans=@()
    $arr=@(1,2,3)

    foreach -parallel ($a in $arr){
       $obj= New-Object System.Object
       $obj | Add-Member -type NoteProperty -Name "Number" -Value $a
       $workflow:ans += $obj
    }
    $ans
}

But the output for this is

PSComputerName                                PSSourceJobInstanceId                                                            
--------------                                ---------------------                                                            
localhost                                     56295d88-4599-495a-ae64-00d129f7e21c                                             
localhost                                     56295d88-4599-495a-ae64-00d129f7e21c                                             
localhost                                     56295d88-4599-495a-ae64-00d129f7e21c   

I want an array that contain three objects. How to achieve this in this scenario

1

There are 1 answers

0
CB. On

try this way:

workflow sample {        
    $ans=@()
    $arr=@(1,2,3)    

    foreach -parallel ($a in $arr){
       $obj= New-Object -type PSObject -Property  @{ 
       Number = $a 
       }
       $workflow:ans += $obj
    }

    $ans     
}

sample | select -Property Number

Add-member doesn't work so well in a workflow probably due to object serialisation/deserialisation.