plunkets
plunkets

Reputation: 550

In Powershell, how to store an object in array, by "value" and not by "reference"?

In one of my scripts, i noticed that when i store a custom object in one array, and then, if i modify the object properties, all changes are made in the array too.

Is there a simple way to store objects by value?

I want to avoid recreating a new object each time i want to store its value.

Example:

PS D:\wamp\www> $obj = New-Module -ScriptBlock { $var1="value1"; Export-ModuleMember -Variable * } -AsCustomObject
PS D:\wamp\www> $arr = @()
PS D:\wamp\www> $arr += $obj
PS D:\wamp\www> $arr

var1
----
value1


PS D:\wamp\www> $obj.var1 = "newvalue"
PS D:\wamp\www> $arr += $obj
PS D:\wamp\www> $arr

var1
----
newvalue
newvalue

PS D:\wamp\www> $obj2 = $obj.Psobject.Copy()
PS D:\wamp\www> $obj2.var1 = "other"
PS D:\wamp\www> $arr += $obj2
PS D:\wamp\www> $arr

var1
----
other
other

Upvotes: 5

Views: 4934

Answers (2)

plunkets
plunkets

Reputation: 550

Finally, i pick a (very simple) solution in the "clone psobject" topic: use the select * when adding value to array. It creates a "custom object" too, but unlike the "psobject.copy" method, doesn't creates a "pointer".

PS D:\wamp\www> $m = New-Module -AsCustomObject -ScriptBlock { $var = "val"; Export-ModuleMember -Variable * }
PS D:\wamp\www> $arr += @()
PS D:\wamp\www> $arr += $m | Select *
PS D:\wamp\www> $m.var = "other"
PS D:\wamp\www> $arr += $m | Select *
PS D:\wamp\www> $arr

var
---
val
other

Upvotes: 1

manojlds
manojlds

Reputation: 301147

When adding to the array, add a copy of the object:

$arr += $obj.PSObject.Copy()

http://msdn.microsoft.com/en-us/library/system.management.automation.psobject.copy(v=vs.85).aspx

Upvotes: 6

Related Questions