PowerShell Sets

A set in PowerShell can contain multiple unique values of the same type and has the ability to grow or shrink automatically. There are two types of set, ‘HashSet’ and ‘SortedSet’, both of which will be discussed here.

The difference between these two types of set is that a ‘HashSet’ doesn’t maintain an order of the items within it, whereas a ‘SortedSet’ does.

Below is an example of how both of these types of set are declared, where ‘$peopleHashSet’ and ‘$peopleSortedSet’ are the names for the respective sets, with each being able to hold string values.

$peopleHashSet = [System.Collections.Generic.HashSet[string]]::new()
$peopleSortedSet = [System.Collections.Generic.SortedSet[string]]::new()

The following are examples of how items can be added to these sets and then subsequently displayed in the terminal using a ‘foreach’ loop. The 'Out-Null' cmdlet is used to suppress unwanted output in the terminal.

$peopleHashSet.Add("George") | Out-Null
$peopleHashSet.Add("Fred") | Out-Null
$peopleHashSet.Add("Bob") | Out-Null
$peopleHashSet.Add("Andew") | Out-Null

$peopleSortedSet.Add("George") | Out-Null
$peopleSortedSet.Add("Fred") | Out-Null
$peopleSortedSet.Add("Bob") | Out-Null
$peopleSortedSet.Add("Andrew") | Out-Null

Write-Host "HashSet:"
foreach ($person in $peopleHashSet) 
{
    Write-Host $person
}

Write-Host ""
Write-Host "SortedSet:"

foreach ($person in $peopleSortedSet) 
{
    Write-Host $person
}

The output from the above is where the difference between the two sets can be seen, where the names in the ‘HashSet’ are in no particular order, but in the ‘SortedSet’ they are displayed alphabetically.

HashSet:
George
Fred
Bob
Andrew

SortedSet:
Andrew
Bob
Fred
George

As previously mentioned, a set cannot contain duplicate items, however, if an attempt is made to add a duplicate, no error is produced, and no new item gets added.

Removing an item from a set is done in a similar fashion to adding.

$peopleHashSet.Remove("Bob") | Out-Null
$peopleSortedSet.Remove("Bob") | Out-Null

If there is a need to check to see if an item exists within a set, then the ‘Contains’ method can be used with both a ‘HashSet’ and a ‘SortedSet’. The ‘Contains’ method is used in the examples below to check for the existence of the name ‘George’ in both the sets and display a message to the terminal if it is found.

if ($peopleHashSet.Contains("George"))
{
    Write-Host "George is in the HashSet"
}

if ($peopleSortedSet.Contains("George"))
{
    Write-Host "George is in the SortedSet"
}