5

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
1

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried that "Copy" too, but the problem is the same: when i update a property, the changes are made in the array. I also tried something like that: PS D:\wamp\www> $obj2 = $obj.PSObject.Copy().var1 = "other" PS D:\wamp\www> $arr += $obj2 PS D:\wamp\www> $arr var1 ---- other other
@plunkets - What you are saying in the comment is not very clear and looks wrong from what I see. Update your question with what you are trying to say with proper formatting.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.