我有一个具有以下结构的哈希表,
$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
请提出实现我的目标的最佳方法!提前致谢
最佳答案
$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
关于powershell - 如何遍历哈希表,该哈希表包含具有键,值的多个数组,并附加另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64207954/