Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Values from Powershell Parallel Foreach Loops

I'm trying to code the following situation in Powershell:

Create array of objects

Parallel foreach of array
{
     Perform work on item of array;
     Assign/return value of work;
}

Perform work on results of Parallel foreach loop

I can't find any clear guides on how to do this, just bits and pieces which myself and two other coworkers can't seem to compile into a working solution, even a simple example solution that we can then apply to the actual work we need to do.

Given a simple task, like taking in an array of ints:

$inputArray = @(1..200)

And then, for each int, multiply it by itself, and return the value for each multiplication in a thread safe manner (as, I assume, an array), how would you code this in Powershell?

Edit: Not to confuse any potential answers, but here's what we've tried to create so far.

$inputArray = @()
$resultArray = @()

for($i = 0; $i -le 10; $i++)
{
    $inputArray += Get-Random
}

Write-Output "Workflow"

workflow ExampleWorkflow
{
    param ($items)

    $test = @()

    foreach -Parallel ($item in $items)
    {
        $WORKFLOW:test += ($item * $item)
        $WORKFLOW:test += ($item + $item)
        $WORKFLOW:test += ($item * 3.14)
    }
    Write-Output ("TEST CURRENT: " + $test[0])
}

ExampleWorkflow $inputArray

Write-Output ("This is test: " + $test)

$resultArray | % { Write-Output $_ }
like image 458
Ranger Avatar asked Apr 15 '26 13:04

Ranger


1 Answers

I'm not 100% clear on what your end goal is on this, but from the code you posted it looks like your trying to randomize values in an array and create a new array from the randomized values. If that's the case try something like what I have below. The $resultArray wasn't getting populated before because it was being initialized outside of your workflow.

$inputArray = @()


for($i = 0; $i -le 10; $i++)
{
    $inputArray += Get-Random
}

Write-Output "Workflow"

workflow ExampleWorkflow
{
    param ($items)

    $test = @()

    foreach -Parallel ($item in $items)
    {
        $WORKFLOW:test += ($item * $item)
        $WORKFLOW:test += ($item + $item)
        $WORKFLOW:test += ($item * 3.14)

    }
    [array]$resultArray = @($test)
    Write-Output ("TEST CURRENT: " + $test[0])
    $resultArray


}




ExampleWorkflow $inputArray 
like image 170
nfernal13 Avatar answered Apr 17 '26 05:04

nfernal13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!