这是我的代码
$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
最佳答案
哈希表是引用,当您创建一个对象时,所有进一步的操作都针对该哈希表,包括尝试检索该信息。
您可以在每次循环运行时声明一个新的哈希表来解决这个问题。
$allTests = New-Object System.Collections.ArrayList
1..10 | foreach {
$singleTest = @{}
$singleTest.add("Type", "Human")
$singleTest.add("Count", $_)
$singleTest.add("Name", "FooBar...whatever..$_")
$singleTest.add("Age", $_)
$allTests.Add($singleTest) | Out-Null
}
甚至可以这样来消除一些臃肿。
$allTests = New-Object System.Collections.ArrayList
1..10 | foreach {
$allTests.Add(@{
Type = "Human"
Count = $_
Name = "FooBar...Whatever..$_"
Age = $_
}) | Out-Null
}
这两个答案都会为您提供预期的输出。
关于loops - 为什么我不能将哈希表存储在数组列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45242067/