在Powershell中,如何通过“值”将对象存储在阵列中。而不是通过“参考”? [英] In Powershell, how to store an object in array, by "value" and not by "reference"?

查看:103
本文介绍了在Powershell中,如何通过“值”将对象存储在阵列中。而不是通过“参考”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个脚本中,我注意到当我在一个数组中存储一个自定义对象时,然后,如果我修改对象属性,那么所有更改也将在数组中进行。



是否有一种简单的方法可以按值存储对象?



我想避免每次想存储对象值时都重新创建一个新对象。 / p>

示例:

  PS D:\wamp\www> $ obj =新模块-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
----
其他
其他


解决方案

最后,我在克隆psobject主题中选择了一个(非常简单的)解决方案:使用 select * 向数组添加值时。它也会创建一个自定义对象,但是与 psobject.copy方法不同,它不会创建指针。

  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 |选择*
PS D:\wamp\www> $ m.var = other
PS D:wamp\www> $ arr + = $ m |选择*
PS D:\wamp\www> $ arr

var
---
val
其他


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

解决方案

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

这篇关于在Powershell中,如何通过“值”将对象存储在阵列中。而不是通过“参考”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆