如何遍历包含具有键、值的多个数组的哈希表并将其附加到另一个字符串?

How to iterate through a hashtable which contains multi arrays with key, values and append it with another string?

我有一个具有以下结构的哈希表,

$testHsh = @{2 = (1,3);3 = (2,4,6)}

我正在尝试迭代上面的哈希表,并希望将字符串“testmachine-”与键值 (2 & 3) 连接起来,并尝试将这些值保存在另一个哈希表中,如下所示,

$tm = @{2 = (testmachine-1,testmachine-3,testmachine-5);3 = (testmachine-2,testmachine-4,testmachine-6)}

这是我实现 objective,

的代码
$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

请提出实现我的 objective 的最佳方法!提前致谢

请参阅 以了解有关枚举哈希表的更多信息。

我会怎么做:

$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