Wednesday, November 13, 2013

PowerShell: Clearing the values within a HashTable without removing construct of Keys

I had an interesting questions posed to me today:

"Is it possible to clear the contents of all the values within a HashTable in PowerShell but retaining the Key names (i.e. the construct of the hashtable)."

This sounds perfectly acceptable but unfortunately there is not native way of doing this and only have the following options:
1) Set the HashTable variable to $null
2) Rebuild the HashTable from a definition with empty values

Neither of these 2 options are very dynamic or suited the application.

The solution I thought was to loop through the HashTable keys collection and modify the value of one of the entities, however that results in:

Collection was modified; enumeration operation may not execute.

Our solution is though to use the .Clone() method of the HashTable to build a copy of it in memory just for the sake of looping through it's entities. Here is my example code:

$hash = @{FirstName="Bob";LastName="Smith";Age="23"}
$hash

#create a clone of the hash table, this avoids the 
# "Collection was modified" enumeration error
$hash2 = $hash.Clone();

#loop through each key in the cloned hastable and update the 
# value in the original table
foreach($key in $hash2.keys){$hash[$key] = '';}

#clear the cloned hashtable to free memory
$hash2 = $null;

#just output the hashtable for verification in this demo
$hash





4 comments:

  1. Ho comprato questa copia di abiti e accessori gucci da questo negozio, repliche gucci sneaker la qualità è molto buona, è stata riacquistata molte volte, repliche donna gucci raccomandata agli amici in giro, tutti lodano la qualità dei vestiti, l'atteggiamento del negozio è buono.

    ReplyDelete
  2. From cool glitter trainers replica boots to decadent velvet sandals, Alexander McQueen shoes for new season are fit replica alexander mcqueen for a dark historical romance. We have selected the key styles of the season to fall for here.

    ReplyDelete
  3. I have always had a good impression of Ray-Ban. I just happened to buy it at this store.buy ray bans wayfarer mens sale I chose this classic, I am very beautiful. After that,mens ray ban wayfarer sunglasses uk I found that the activity price was 50% cheaper than usual or other e-commerce. Very valuable

    ReplyDelete