Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set (data structure) in PowerShell

Tags:

powershell

set

People also ask

Does set work in PowerShell?

In PowerShell, Set is an alias for the Set-Variable cmdlet, but it doesn't work with environment variables. Instead, you have to use the Get-ChildItem, Get-Item, or Remove-Item cmdlet with the ENV: drive.

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What are data types in PowerShell?

PowerShell data types include integers, floating point values, strings, Booleans, and datetime values. Variables may be converted from one type to another by explicit conversion, such as [int32]$value .


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


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]]@()