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





7 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
  4. This replica jimmy choo shoe is perfect in quality and comfortable to wear.jimmy choo shoes uk You can wear this shoe when you travel, and you will not feel tired.replica jimmy choo wedges I recommend this site to my good friends, they are very happy to be able to buy such cheap Jimmy Choo shoes

    ReplyDelete
  5. What makes Giuseppe Zanotti pumps, Giuseppe Zanotti sandals, replica giuseppe zanotti uk and Giuseppe Zanotti boots so unique is cheap man giuseppe zanotti espadrilles their consummate synthesis of design awareness and quality: "design awareness keeps you up to speed with the major trends that, season after season, dominate the worlds of ready-to-wear and haute couture; and it's also important for building up a repertory of ideas and images taken from music videos, from art, the cinema, from design, in short from everything which reflects changing fashions," explained Zanotti. "Technique and taste work in a reciprocal relationship, allowing all these ideas to come together."

    ReplyDelete
  6. Ha sido un hito en la industria desde que Longines estableció su marca en Saint-Imier en 1832.relojes réplica Hoy, la marca ofrece una variedad de relojes para hombres y mujeres. longines relojes réplicaLos relojes Longines se han utilizado a lo largo de la historia, desde la aventura hasta la expresión elegante. Además de ser conocido por su conexión con el mundo de las carreras y la equitación, Longines también es conocido mundialmente por su refinamiento elegante y atemporal. Tenemos una variedad de relojes Longines a la venta, todos nuevos, hermosos y garantizados para ser auténticos. Aún mejor, cuando compra Longines en línea, sabe que está obteniendo el mayor valor. Explore nuestra lista de selección para encontrar los mejores precios de relojes en Longines en Internet.

    ReplyDelete