Melvin ceylan
Melvin ceylan

Reputation: 29

Array in Powershell - Cant read each value by corresponding with a second array

I'm working on a project,

I have 3 arrays, and i want to take all values from it. maybe some code would be better than explanation.

$Array1= "Value1", "Value2", ....
$Array2= "Another1", "Another2",...
$Array3= "Again1", "Again2", ...

My result should be

Value1 Another1 Again1
Value2 Another2 Again2

etc...

I've tried many option like so :

foreach($i in $Array1){
  Foreach($j in $Value2){
     Write-host $i "," $j
   }
} 

result:
Value1, Another1
Value1,Another2
Value2,Another1
Value2,Another2

I've search a solution for like 5 hours . and i'm not an expert in powershell. please help me !!

Upvotes: 0

Views: 33

Answers (1)

Theo
Theo

Reputation: 61068

You need to make sure either all arrays have the same number of elements, or take the minimum amount of elements to loop through:

$Array1= "Value1", "Value2" #
$Array2= "Another1", "Another2"#
$Array3= "Again1", "Again2"#

# make sure you do not step out of index on one of the arrays
$items = [math]::Min($Array1.Count, [math]::Min($Array2.Count, $Array3.Count))

for ($i = 0; $i -lt $items; $i++) {
    # using the -f Format operator gives nice-looking code I think
    '{0},{1},{2}' -f $Array1[$i], $Array2[$i], $Array3[$i]
}

Result:

Value1,Another1,Again1
Value2,Another2,Again2

Upvotes: 1

Related Questions