Powershell: How to add Result to an Array (ForEach-Object -Parallel)

Question:

I know, that with the Parameter $using:foo I can use a Variable from a different runspace while running ForEach-Object -Parallel in Powershell 7 and up.

But how can I add the result back to a Variable? The common parameters += and $using: will not work.

For instance:


Output:

Answer:

You will have to split the operation into two and assign the reference you get from $using:Costs to a local variable, and you will have to use a different data type than PowerShell’s resizable array – preferably a concurrent (or thread-safe) type:

Source:

Powershell: How to add Result to an Array (ForEach-Object -Parallel) by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply