You need to clone $object1
in order to obtain an independent copy of it:
$object2 = $object1.Clone() # assumes that $object's type implements ICloneable
[System.Xml.XmlDocument]
is a reference type (as opposed to a value type such as [int]
), which means that:
$object2 = $object1
simply makes $object2
reference (point to) the very same object as $object1
.
You can verify this as follows:
[object]::ReferenceEquals($object1, $object2)
Generally:
=
with a value type instance creates a copy of the actual value, i.e., it implicitly clones.
=
with a reference type instance creates a copy of the reference to the instance, i.e., it creates another reference to the very same object.
The same applies when you add elements to a (mutable) collection; e.g. (assume having created a list with $list = [System.Collections.Generic.List[object]] @()
):
$var = 42; $list.Add($var)
adds a copy of the value-type ([int]
) instance to the list.
$var = [pscustomobject] @{ foo = 'bar' }; $list.Add($var)
adds a reference to the reference-type ([pscustomobject]
) instance to the list.
To determine if a given type is a value type or a reference type, use the type's Boolean .IsValueType
property:
# Inspect a type directly.
PS> [System.Xml.XmlDocument].IsValueType
False # -> a *reference* type
# Inspect a type via an instance thereof:
PS> $xml = [xml] '<xml/>'; $xml.GetType().IsValueType
False