Removing elements from a hashtable

Unlike arrays, removing an element from a hashtable is straightforward—an element is removed using the Remove method:

$hashtable = @{ Existing = "Existing" } 
$hashtable.Remove("Existing") 

If the requested key does not exist, the command does nothing (and does not throw an error).

The Remove method cannot be used to modify the hashtable while looping through the keys in a hashtable using the Keys property:

PS> $hashtable = @{
Key1 = 'Value1'
Key2 = 'Value2'
}
PS> foreach ($key in $hashtable.Keys) {
$hashtable.Remove($key)
}

Collection was modified; enumeration operation may not execute.
At line:5 char:10
+ foreach ($key in $hashtable.Keys) {
+ ~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException

The same method as discussed in the Adding and changing elements to a hashtable section, may be used.

Finally, a hashtable may be emptied completely by calling the Clear method:

$hashtable = @{one = 1; two = 2; three = 3} 
$hashtable.Clear() 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.35.75