Forum Discussion

rahulruns's avatar
rahulruns
Copper Contributor
Feb 19, 2019

read elements of an array simultaneously

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

  • Darrick's avatar
    Darrick
    Brass Contributor

    rahulruns 

     

    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=powershell-6

  • 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().

    • rahulruns's avatar
      rahulruns
      Copper Contributor

      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

      • Kevin_Morgan's avatar
        Kevin_Morgan
        Iron Contributor

        Hi,

        You can achieve this by "join" method.

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

        $testarray -join " "

        #For comma separated values

        $testarray -join ","

         

Resources