Powershell - 2 arrays

jaime29 1 Reputation point
2021-09-03T16:06:01.147+00:00

How will I write a code with 2 arrays where 1st array has 50 items and 2nd array has 7 items

Condition: for each item in Array 1 will assign 1 item from array 2, then 2nd item in array 1 and 2nd item in array 2..... and so on,

when 7th item in array 2, array 2 will reset to 1st item for item 8th in array 1.

Sample output

a = 1a
b = 2a
c = 3a
d = 4a
e = 5a
f = 6a
g = 7a
h = 1a
i = 2a
j = 3a
k = 4a
l = 5a
.........

Currently my 2nd array loop isn't working at all :(

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,463 questions
{count} votes

3 answers

Sort by: Most helpful
  1. MotoX80 32,911 Reputation points
    2021-09-03T17:22:13.787+00:00
     $Array1 = @('a','b','c','d','e','f','g','h','i','j','k','l','m')
     $Array2 = @('1a','2a','3a','4a')
    
     $A2Idx = 0                          # Point to first entry in the second array 
     Foreach ($a1 in $Array1) {
         "{0} = {1}" -f $a1, $Array2[$A2Idx]
         $A2Idx++                        # Point to the next entry in the second array 
        if ($A2Idx -eq $Array2.count) {  # At end? 
            $A2Idx = 0                   # Point back to first entry in the second array 
        }      
     }
    
    0 comments No comments

  2. Andreas Baumgarten 104K Reputation points MVP
    2021-09-03T17:37:48.627+00:00

    Hi @jaime29 ,

    maybe this helps:

    $a = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o')  
    $b = @('1a', '2a', '3a', '4a', '5a', '6a', '7a')     
    $bI = 0  
    $result = @()  
    Foreach ($item in $a) {  
        $result += $item, $b[$bI] -join "="  
        $bI++  
        if ($bI -eq $b.count) {   
            $bI = 0  
        }        
    }  
    $result  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

  3. Limitless Technology 39,516 Reputation points
    2021-09-06T07:37:43.923+00:00

    Hi there,

    Use the + operator to add to arrays together:

    PS C:\> $a = 2,3,4

    PS C:\> $b = 5,6,7

    PS C:\> $c = $a + $b

    PS C:\> $c

    Hope this Answers all your queries , if not please do repost back .
    If an Answer is helpful, please click "Accept Answer" and upvote it : )