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.
@{} 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'
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.
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]]@()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With