Copy or clone a hashtable?

I thought the following line of code would make the job.

$HastTable2 = $HastTable1

However, despite at first glance it works fine, it has some unexpected consequences: both objects are now bound and any changes made to one of them is also made to the other one.

To convince you, try the following script which does followings:

  1. Create a hashtable WeatherNY
  2. Executes the line $WeatherLA = $WeatherNY
  3. Add the value Humidity to hashtable WeatherNy
  4. Add the value Wind to hashtable WeatherLA
  5. Display the content of both hashtables
$WeatherNY =@{
SkyColour = 'Blue'
Temperature = 90
}

$WeatherLA = $WeatherNY

$WeatherNY.Add('Humidity',30)

$WeatherLA.Add('Wind',14)

"`r`nNY weather&quot $WeatherNY"

"`r`nLA weather $WeatherLA"

As you can notice in the output, both objects contain the same values.

copy hashtable

In fact, in this case, I had to use the Clone method and replace the line
$WeatherLA = $WeatherNY
with this one
$WeatherLA = $WeatherNY.Clone()

Here is the final output

copy hashtable with clone method

More about

Hashtable.Clone Method (MSDN)

Powershell: Everything you wanted to know about hashtables (Kevin Marquette)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s