read elements of an array simultaneously

Copper Contributor

Hi All,

I am PS newbie (though have worked on other languages). Is there a way we can read elements of an array simultaneously rather than iterating through a foreach loop. I have an array ("A" , "B" , "C" , "D"), instead of iterating like foreach ($x in $array) { print $x}, is it possible that I pull our all simultaneously

8 Replies

Not sure exactly what you mean, you can get all the elements by simply referencing the array variable? Or use something like $testarray.GetEnumerator() or $testarray.Split().

Thanks for your reply Vasil, here is what I have (sample code)

$testarray = ("a", "b", "c", "d")

foreach ($x in $testarray) {

    print $x

}

This loop actually iterates this array and prints 

a

b

c

d

Now I wanted to perform it in a way that this print statement is executed on all elements at once and  so that result is like

a b c d

Hi,

You can achieve this by "join" method.

$testarray = ("a", "b", "c", "d")

$testarray -join " "

#For comma separated values

$testarray -join ","

 

powershell-join-array-string.png

Thank you for your reply, I will try to be clearer on what I intent to do.  $testarray (with join it will have field separators) will print array but will not help me do a simultaneous operation on all elements of an array. What I wrote is just sample where if I replace print statement with anything else it should work on all elements simultaneously

What exactly are you trying to do?

Hi Vasil,
I have a function that performs some operation on each element of an array. Now these operations are independent and not required to be done simultaneously.  I am trying to work out a method that how function can act on all these elements at same time

For this case, you have to use asynchronous function call. I think you can do it by using Start-Job.
$function = {
param($a)
Write-Host $a
}

$testarray = ("a", "b", "c", "d")
$testarray | ForEach-Object {
Start-Job -ScriptBlock $function -ArgumentList $_
}
#Run below command to remove jobs and get result
Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id }
You can also explore how to achieve this from below threads.
https://stackoverflow.com/questions/12766174/how-to-execute-a-powershell-function-several-times-in-parallel
https://blogs.technet.microsoft.com/uktechnet/2016/06/20/parallel-processing-with-powershell/

Hopefully @Vasil Michev know more about this requirement.