Search code examples
powershellpowershell-3.0powershell-4.0

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


I have a hashtable with the below structure,

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

I'm trying to iterate the above hashtable and wanted to concatenate the string "testmachine-" with the values of keys(2 & 3)and trying to save the values in another hashtable like below,

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

Here is my code to achieve my 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

Please suggest the best method to achieve my objective! Thanks in advance


Solution

  • See this post to learn more about enumerating hashtables.

    How I'd do it:

    $testHsh.GetEnumerator() | foreach {
        $machineHash[$_.Key] = $_.Value | foreach {"$teststr$_"}
    }
    

    If you need more explanation, let me know in a comment.