Reputation: 29
I'm new to powershell, and I am learning how to use for loops function. here is the script:
$arys = @( 1, 2, 3, 4, 5)
for ($i=0; $i -le $arys.Length – 1; $i++)
{Write-Host $arys[$i]}
The only thing I don't understand is this part:
$arys[$i]
-> what is the explanation of this script? I mean I can see $arys
and $i
are variables, but why is $i
needs to be put inside the closing brackets []
?
Upvotes: 1
Views: 90
Reputation: 47772
$i
contains the number in the current iteration of the loop. The loop counts from 0
through the length of the array.
To get the item from the array, you must ask the array for the item at index $i
, hence $arys[$i]
. Square brackets are the indexing operator for arrays.
So for example if the value of $i
were 3, you would get get $arys[3]
which the value 4
(because the array is indexed starting at 0
).
This might be more apparent if you use an array of strings instead of numbers like $arys = @( 'A', 'B', 'C', 'D', 'E' )
.
Upvotes: 1