Cloning Objects

by May 6, 2009

As a rule of thumb, PowerShell creates real copies when you copy variables. So in the next example, changing the array in $a will not affect the copy in $b:

$a = 1..10
$b = $a
$a += 11
$b

Complex objects, such as hash tables, are not copied this way, though. Instead, PowerShell uses the very same reference. In the next example, changing the hash table in $a will also affect $b because both variables point to the very same hash table:

$a = @{}
$a.Test = 1
$a.Value = 2
$b = $a
$a.New = 3
$b

You can create an explicit copy of a hash table (or any other complex object) by creating a clone. Most objects provide the Clone() method to do just that:

$a = @{}
$a.Test = 1
$a.Value = 2
$b = $a.Clone()
$a.New = 3
$b