【发布时间】:2017-07-21 16:00:29
【问题描述】:
这是我的代码
$allTests = New-Object System.Collections.ArrayList
$singleTest = @{}
$singleTest.add("Type", "Human")
1..10 | foreach {
$singleTest.add("Count", $_)
$singleTest.add("Name", "FooBar...whatever..$_")
$singleTest.add("Age", $_)
$allTests.Add($singleTest) | out-null
$singleTest.remove("Count")
$singleTest.remove("Name")
$singleTest.remove("Age")
}
根据我的理解,我的循环应该在每次到达时将哈希表的副本添加到数组列表中
$allTests.Add($singleTest) | out-null
循环继续,删除一些键,这为循环的下一次迭代铺平了道路。这不是发生的事情,就像 add 命令只是添加对哈希表的引用。
如果我检查
的最终值$allTests
这会被退回
Name Value
---- -----
Type Human
Type Human
Type Human
Type Human
Type Human
Type Human
Type Human
Type Human
Type Human
Type Human
如何解决这个问题,以便将哈希表的实际副本存储在数组列表中?
我正在寻找类似的输出
$allTests[0]
Name Value
---- -----
Count 1
Name FooBar...whatever..1
Age 1
Type Human
$allTests[1]
Name Value
---- -----
Count 2
Name FooBar...whatever..2
Age 2
Type Human
【问题讨论】:
-
在 Powershell 哈希表中是引用对象。您基本上必须创建一个新的哈希表并遍历旧的哈希表并将信息从旧的复制到新的。
$oldHash = @{} $newHash = @{} $newHash = $oldHash执行上述操作只会使$newHash引用$oldHash并且对$newHash的任何更改都将出现在$oldHash中 -
这些可能有用:Reference v Value Types、about_Hash_Tables 和 the Hashtable .NET class(包括克隆方法)
标签: loops powershell arraylist hashtable