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 $_ }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With