PowerShell Arrays
An array is a list of values stored under one variable name. Each value sits at a numbered position called an index.
Build an array and read by index
The first value sits at index zero. The third value sits at index two.
$colors = @("red", "green", "blue")
$colors[0]
$colors[2]Read the last value and the count
Index -1 means the last value. Count tells how many values the array holds.
$colors = @("red", "green", "blue")
$colors[-1]
$colors.CountChange one value and print the array
Assign a new value at an index to replace it. Join prints the whole array on one line.
$colors = @("red", "green", "blue")
$colors[1] = "yellow"
$colors -join ", "Example
$names = @("Ana", "Ben", "Cid")
$names[1] = "Bo"
$names -join ", "
$names.Count
$names[-1]Key points
- Array: a list of values held in a single variable.
- Index: the numbered position of a value in an array, starting at zero.
- Use @() to build an array, with commas between the values.
- Read a value by writing the array name and its index in square brackets.
- The index -1 always means the last value in the array.
- Count: a property that tells how many values an array holds.
In this example, an array of three names is built first. The middle name is replaced with Bo, then the whole array prints on one line. The count prints next, and the last name prints last.
Note
changing a value at one index leaves the other values untouched.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is $a[0] when $a = @("cat", "dog", "fish")?