Feb 19 2019 01:36 AM
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
Feb 19 2019 10:29 AM
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().
Feb 19 2019 08:59 PM
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
Feb 19 2019 11:24 PM - edited Feb 19 2019 11:26 PM
Hi,
You can achieve this by "join" method.
$testarray = ("a", "b", "c", "d")
$testarray -join " "
#For comma separated values
$testarray -join ","
Feb 19 2019 11:49 PM
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
Feb 20 2019 12:15 AM
What exactly are you trying to do?
Feb 21 2019 01:09 AM
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
Feb 21 2019 01:47 AM - edited Feb 21 2019 01:50 AM
$function = {
param($a)
Write-Host $a
}
$testarray = ("a", "b", "c", "d")
$testarray | ForEach-Object {
Start-Job -ScriptBlock $function -ArgumentList $_
}
Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id }
Mar 27 2019 08:57 AM
Take a look at these.
Runspaces: https://github.com/proxb/PoshRSJob
PowerShell Jobs: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=p...