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

不打扰是莪最后的温柔 提交于 2020-01-02 09:38:01

问题


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:


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




回答2:


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


来源:https://stackoverflow.com/questions/18034689/in-powershell-how-to-store-an-object-in-array-by-value-and-not-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!