1 Reply Latest reply on Jun 19, 2018 2:11 PM by tszilagyi

    Creating an array in a powershell script

    tszilagyi

      I am trying to figure out a way to dynamically create an array from several variables inside of a powershell script.

       

      I have several variables that will be deffined

       

      $svr_list1 = "svrA", "svrB", "svrC"

      $svr_list2 = "svrD", "svrE"

      $svr_list3 = "svrF", "svrG"

       

      $svc_list1 = "svcA", "svcB"

      $svc_list2 = "svcA", "svcC"

      $svc_list3 = "svcD"

       

      I am trying to figure out some list that can pull these together into a single array but only have single groups line up so all servers in svr_list1 will only get the services in svc_list1, list 2 will line up, etc

       

       

      $arry =   [svrA][svcA]

                     [svrA][svcB]

                     [svrB][svcA]

                     [svrB][svcB]

                     [svrC][svcC]

                     [svrC][svcB]

                     [svrD][svcA]

                     [svrD][svcC]

                     [svrE][svcA]

                     [svrE][svcC]

                     [svrF][svcD]

                     [svrG][svcD]

       

       

      I would like to loop this so that i can just update my original variables that are used elsewhere and then this loop would pull together the appropriate list without having to manage it twice. 

        • Re: Creating an array in a powershell script
          tszilagyi

          Ok i found some code that I was able to put together that seems to solve this issue.  Posing it here if anyone has any improvements or could use it as well.

           

           

          $sufixes = @('list1', 'list2', 'list3')

           

          $svr_list1 = "svrA", "svrB", "svrC"

          $svr_list2 = "svrD", "svrE"

          $svr_list3 = "svrF", "svrG"

           

          $svc_list1 = "svcA", "svcB"

          $svc_list2 = "svcA", "svcC"

          $svc_list3 = "svcD"

           

          foreach ($sufix in $sufixes)

          {

          $svr_var = Get-Variable svr_$sufix -valueonly

          $svc_var = Get-Variable svc_$sufix -valueonly

           

               foreach ($i in $svr_var)

               {

                    foreach ($j in $svc_var)

                    {

                         $array += ,@($i,$j)

                    }

               }   

          }

           

          $array

           

           

           

          This seems to update accordingly for me, now in my code i just need to maintain the server and service lists and if i add a new one just update and add the additional suffix.  I did see something about using array lists being better than the " += " functionality as it needs to duplicate the array in memory however my lists are pretty small right now.