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

问题描述

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

$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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...