Reputation: 902
I have 2 dimension array. I would like to get each value of array. I tried this, but each array in $Name has all the array in $Date. But my expectation first item in $Name equal to first item in $Date. This is my expectation result:
A\11
B\12
C\13
$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed
foreach ($na in $Name)
{
foreach ($dt in $Date)
{
$NameAndDate = "$na\$dt"
Write-Host $NameAndDate
}
}
but from the code above I got this result
A\11
A\12
A\13
B\11
B\12
B\13
C\11
C\12
C\13
Anyone can help, please. Thank you
Upvotes: 0
Views: 626
Reputation: 61253
When combining two arrays, both having a non-fixed number of elements, you need to make sure you do not index beyond any of the arrays indices.
The easiest thing here is to use an indexed loop, where you set the maximum number of iterations to the minimum number of array items:
$Name = "A", "B", "C" # the size of this array not fixed
$Date = "11", "12", "13" # the size of this array not fixed
# make sure you do not index beyond any of the array indices
$maxLoop = [math]::Min($Name.Count, $Date.Count)
for ($i = 0; $i -lt $maxLoop; $i++) {
# output the combined values
'{0}\{1}' -f $Name[$i], $Date[$i]
}
Output:
A\11
B\12
C\13
Upvotes: 1
Reputation: 1788
Try this
$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed
foreach ($i in 0..($Name.Count -1)) {
write-host ($Name[$i] + "\" + $Date[$i])
}
Upvotes: 1