Now that we have an array, how do we access items from it?
Indexing
The easiest way to access an item from an array is to use its index number. An index is the position number of an item. Consider the example below:
$colors = "red", "yellow", "black", "blue" #. 0 1 2 3
The numbers underneath the items represent their indices. An array’s indices always start at 0
. If we want to access black
, for example, we must offset – or skip – 2
times.
PS > $colors[2] black
As shown above, the syntax for accessing an array item in PowerShell involves brackets [ ]
. If we provide an index that is out of bounds, such as 10
, PowerShell will not create an error but instead return $null
. The $null
value would result in no output if printed to the terminal but has other behaviors depending on the situation.
Each array object has a Length
property that gives us the number of items in that array. The property Count
will return the same value.
Updating Items
We can also update items by utilizing indices. To change the color yellow
to brown
, for example:
PS > $colors[1] = "brown" PS > $colors red brown black blue
Special Index Tricks
PowerShell offers much more flexibility when indexing items such as
Multiple indices: separate indices with commas to print multiple items:
PS > $colors[0,2] red blackThe example above displays the values at index
0
and2
.Range operator
..
: print all items between two indices:PS > $colors[1..3] brown black blueThe above example displays the values from index
1
to index3
.Reverse range: use range operator from a higher index to a lower index to print items in reverse order (inclusive)
PS > $colors[2..1] black brownThe above example displays the values from index
2
to index1
.Negative indices: items are referenced in reverse order where the last item has index
-1
PS > $colors[-1] blueThe above example displays the value in the last index,
3
.
Iteration
Each array object has a method called ForEach
that allows us to perform the same action on each array item. We can use the variable PSItem
or underscore _
to refer to each item in the array.
PS > $colors.ForEach({ $PSItem.Length }) 3 5 5 4
The example above is printing the length of each string of our colors
array. red
has a length of 3
, brown
is 5
, and so on.
Instructions
In the open PowerShell script, assign the variable favorite
to pho
using indexing.
Click Run to continue.
Change curry
to samosa
in the food
array using indexing.
Click Run to move on to the next checkpoint.
Create a variable named fast_food
and assign the items pizza
, burrito
, and fries
from the food
array.
Use the multiple indices trick.
Click Run to move on.
Create a variable named reverse_food
that holds the food
array in reverse order.
Use the reverse range trick.
Click Run when you are done.
Use iteration on the fast_food
array. Inside the curly braces, write the following:
"Fast foods: " + $PSItem
Click Run when you are done.