PowerShell Arrays

In PowerShell, an array is a special type of variable, or data structure as it is often called, that contains multiple values of the same type. The following string variable, ‘fname’, has been defined and initialised with the name ‘Bob’.

$fname = "Bob"

If multiple names need to be stored, instead of having a different variable for each, an array could be used. As with other variables, it isn’t necessary to explicitly state the type of data that the array can hold, although if this is done, the data type cannot be changed.

# Array without a data type specified.
$fname = "Bob", "George", "Fred", "Alan"

# Array with a data type specified.
[string[]]$fname = "Bob", "George", "Fred", "Alan"

Each value in an array has an index value, which starts at zero for the first item, one for the second and so on. This index value can be used to access an individual item in an array, for example, to display the second item, “George”, in the above array, the index value one can be used.

Write-Host $fname[1]

As well as being able to access individual items in an array, it is also possible to use a special type of ‘for’ loop, called a ‘foreach’ loop, to process all the values that it contains.

foreach ($name in $fname)
{
    Write-Host $name
}

Here, all the names in the array are displayed, one after the other, on separate lines.

Bob
George
Fred
Alan

It is possible to process an array using one of the other loops, such as an ordinary ‘for’ loop and produce the same results, however, the ‘foreach’ loop is the most efficient. Here the ‘length’ property of the array is used in the condition of the loop.

for ($i = 0; $i -lt $fname.Length; $i++)
{
    Write-Host $fname[$i]
}

If it is only necessary to process part of an array, then a range operator can be used to specify the range of index values required. Here, only the values with an index of one and two, “George” and “Fred”, are displayed.

foreach ($name in $fname[1..2])
{
    Write-Host $name
}

It is also possible to use negative values in the range, so minus one refers to the last item, minus two refers to the second to last item and so on.

foreach ($name in $fname[-3..-1])
{
    Write-Host $name
}

In order to add an extra value to the end of an array, the ‘+=’ assignment operator can be used.

$fname += "Fiona"

As well as using the index value to access a particular element of an array, it can also be used to change a particular value, for example, the value at index position one.

$fname[1] = "Sophie"