0

I have an hashtable with a below structure,

$podhashtable = @{2 = '1','2' ; 3 = '3','4','5' ; 1 = '6'}

Here is the code how I achieve the above hashtable,

$podnumbers = @(2,3,1)
$podInfo = @()
$podhashtable = [ordered]@{}
$buff = 0
foreach ($pd in $podnumbers) {
    #$podInfo = @()
    for($i=0;$i -lt $pd;$i = $i+1) {
    $pod = Read-Host -Prompt "Assign the pod numbers for",$esxarray[$buff]
    $podinfo += $pod
    }

$podInfoOb = New-Object PSObject –Property $podsets
$podsets = @{$pd = $podInfo}
$podhashtable += $podsets
$buff = $buff + 1
}
Write-Output $podhashtable 

I'm trying to create array of hashtable like below,

$podhashtable = @{2 = '1','2'}, @{3 = '3','4','5'}, @{1 = '6'}

What is the best way to get the above array of hashtable?

1 Answer 1

0

This question apparently refers to: How to add same keys with different values to a hashtable in powershell?

I guess you want to do this:

$buff = 0
$podnumbers = @(2,3,1,2)
$podhashtable = foreach ($pd in $podnumbers) {
    $podInfo = @{}
    for($i=0; $i -lt $pd; $i = $i+1) {
        $pod = Read-Host -Prompt "Assign the pod numbers for" # , $esxarray[$buff]
        $podinfo[$i] = $pod
        # $podInfoOb = New-Object PSObject –Property $podsets
        $podInfo
        $buff = $buff + 1
    }
}
Write-Output $podhashtable

But I can't be sure as you didn't supply a MCVE (please do so next time; e.g.: define $esxarray or leave it out).

Sign up to request clarification or add additional context in comments.

4 Comments

Actually yes, but as per the question you referenced didn't satisfy my objective coz hashtable doesn't allow duplicate keys. Though of using arrays of hashtable so I can add duplicate keys with different values
I am not sure whether I understand what the issue remains. I have added a duplicate key ($podnumbers = @(2,3,1,2)) to the (updated) answer, which is based on 2. or you might create a list (array) of hash tables
i have tried your method which allows adding duplicate keys but it merges the values of duplicate keys together, I wish to add duplicate keys with different values and represent the keys independently
You can do that by placing the $podInfo (and $buff = $buff + 1) inside the for loop. (I have updated the answer accordingly).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.