Adding and changing elements to a hashtable

Elements may be explicitly added to a hashtable using the Add method:

$hashtable = @{} 
$hashtable.Add("Key1", "Value1") 

If the value already exists, using Add will generate an error (as shown here):

PS> $hashtable = @{"Existing", "Value0"}
PS>
$hashtable.Add("Existing", "Value1")

Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'Existing' Key being added: 'Existing'"
At line:2 char:1
+ $hashtable.Add("Existing", "Value1")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException

The Contains method will return true or false, depending on whether or not a key is present in hashtable. This may be used to test for a key before adding:

$hashtable = @{} 
if (-not $hashtable.Contains("Key1")) { 
    $hashtable.Add("Key1", "Value1") 
} 

Alternatively, two different ways of adding or changing elements are available. The first option is as follows:

$hashtable = @{ Existing = "Old" } 
$hashtable["New"] = "New"            # Add this 
$hashtable["Existing"] = "Updated"   # Update this 

The second option is as follows:

$hashtable = @{ Existing = "Old" } 
$hashtable.New = "New"               # Add this 
$hashtable.Existing = "Updated"      # Update this 

If a value only has to be changed if it exists, the Contains method may be used:

$hashtable = @{ Existing = "Old" }
if ($hashtable.Contains("Existing")) {
$hashtable.Existing = "New" }

This may also be used to ensure a value is only added if it does not exist:

$hashtable = @{ Existing = "Old" }
if (-not $hashtable.Contains("New")) {
$hashtable.New = "New" }

Keys cannot be added nor can values be changed while looping through the keys in a hashtable using the keys property. Doing so changes the underlying structure of the hashtable, invalidating the iterator:

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

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

It is possible to work around this problem by first creating an array of the keys, as follows:

$hashtable = @{ 
    Key1 = 'Value1' 
    Key2 = 'Value2' 
} 
[Object[]]$keys = $hashtable.Keys 
foreach ($key in $keys) { 
    $hashtable[$key] = "NewValue" 
} 

Notice that the highlighted keys variable is declared as an array of objects. Earlier in this chapter, we discussed assigning objects to variables, and how an assignment does not always create a new instance of an object. Using the Object[] type conversion forces the creation of a new object (a new array of objects) based on the values held in KeyCollection. Without this step, the preceding error message would repeat.

Another approach uses the ForEach object to create a new array of the keys:

$hashtable = @{ 
    Key1 = 'Value1' 
    Key2 = 'Value2' 
} 
$keys = $hashtable.Keys | ForEach-Object { $_ } 
foreach ($key in $keys) { 
    $hashtable[$key] = "NewValue" 
} 
..................Content has been hidden....................

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