PowerShell Lists
A list in PowerShell can contain multiple values of the same type and is ideal for storing and retrieving large numbers of elements. They can grow and shrink automatically, whilst containing multiple null and duplicate values if necessary.
The example below creates a list of strings called ‘people’, adds four names, then, using a ‘foreach’ loop, displays the names in the terminal.
$people = [System.Collections.Generic.List[string]]::new() $people.Add("George") | Out-Null $people.Add("Fred") | Out-Null $people.Add("Bob") | Out-Null $people.Add("Andew") | Out-Null foreach ($person in $people) { Write-Host $person }
The output from this will be as follows.
George Fred Bob Andew
Each element in a list has an index value, which starts at zero for the first element. This can be used to access individual elements stored within. Here the second element with an index value of one is displayed in the terminal.
Write-Host $people[1]
If it is necessary to add an item into a list at a specific index position, this is possible using the 'Insert' method. The index position increases by one for all subsequent elements.
$people.Insert(2, "Fiona")
In order to check if a value exists within a list, the 'Contains' method can be used. This returns a Boolean 'True' or 'False' value. This value is displayed out to the terminal in the below example, however, a more common use would be in 'if' statements.
Write-Host $people.Contains("Bob")
To place the elements within a list in order, there is a 'Sort' method that can be used to achieve this.
$people.Sort()
As well as adding and inserting values, the index value can also be used to remove a specific element.
$people.RemoveAt(2)
An alternative method of removing an element from a list is by specifying the value itself. Note that, if duplicate values exist, only the first occurrence of the specified value will be removed.
$people.Remove("George") | Out-Null
Finally, if it is necessary to remove all items in a list in one go, instead of individually, there is a ‘Clear’ method to accomplish this.
$people.Clear()