问题描述
$testHsh = @{2 = (1,3);3 = (2,4,6)}
我正在尝试迭代上述哈希表,并希望将字符串“ testmachine-”与keys(2&3)的值连接起来,并试图将这些值保存在另一个哈希表中,如下所示,
$tm = @{2 = (testmachine-1,testmachine-3,testmachine-5);3 = (testmachine-2,testmachine-4,testmachine-6)}
这是我实现目标的代码,
$teststr= "testmachine-"
$testInfo = $null
$machineHash = @{}
foreach ($ts in $testHsh.Count) {
$testInfo = @()
for($i=0;$i -lt $ts.Values;$i = $i+1) {
$testInfo += @($teststr+ $ts)
Write-Output $testInfo
}
$testInfoSet = @{$ts = $testInfo}
$testInfoObj = New-Object psobject -Property $testInfoSet
$machineHash = $testtInfoObj
}
Write-Output $machineHash
请提出实现我目标的最佳方法!预先感谢
解决方法
请参见this post,以了解有关枚举哈希表的更多信息。
我该怎么做:
$testHsh.GetEnumerator() | foreach {
$machineHash[$_.Key] = $_.Value | foreach {"$teststr$_"}
}
如果您需要更多说明,请在评论中告诉我。
, $testHsh.Count
是一个整数,不是可以迭代的集合。
相反,您需要在源哈希表上调用GetEnumerator()
:
# define source hashtable
$testHsh = @{2 = (1,3,5);3 = (2,4,6)}
# define new destination hashtable
$machineHash = @{}
# loop over each name-value entry in $testHsh
foreach($entry in $testHsh.GetEnumerator()){
# Assign to the same key in the destination hash,an array of the values from the source,but modified
$machineHash[$entry.Name] = @(
# prefix all values from source hash entry with "testmachine-"
$entry.Value |ForEach-Object {
"testmachine-${_}"
}
)
}
$machineHash