Set (data structure) in PowerShell

Hashset is what you are looking for if you want to store only unique values in an array with relatively faster add, remove and find operations. It can be created as -

$set = [System.Collections.Generic.HashSet[int]]@()

You can use the .NET HashSet class that is found under System.Collections.Generic:

$set = New-Object System.Collections.Generic.HashSet[int]

The collection guarantees unique items and the Add, Remove, and Contains methods all operate with O(1) complexity on average.


If you prefer to stick with native PowerShell types, you can use HashTable and just ignore the key values:

# Initialize the set
$set = @{}

# Add an item
$set.Add("foo", $true)

# Or, if you prefer add/update semantics
$set["foo"] = $true

# Check if item exists
if ($set.Contains("foo"))
{
    echo "exists"
}

# Remove item
$set.Remove("foo")

For more information see: https://powershellexplained.com/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about/#removing-and-clearing-keys

Tags:

Powershell

Set