How to get array of object's keys and values in powershell script?

9.6k Views Asked by At

I have an array of object in a below format

$test = @(2 :{1,3,5}, 3 : {2,4,6})

I want to extract objects of keys and values from $test array.

Here is my powershell script to perform the above task,

$testnumbers = @(2,3)
$testStores = @{}
$testInfo = $null
foreach ($tn in $testnumbers) {
    $testInfo = @{}
    for($i=0;$i -lt $tn;$i = $i+1) {
    $testPrompt = Read-Host -Prompt "Assign the test numbers"
    $testInfo += $testPrompt
    }
$testInfoSet = {$tn = $testInfo}
$testInfoObj = New-Object psobject –Property $testInfoSet
$testStores += $testInfoObj
}

Please provide a solution, Thanks in advance!

2

There are 2 best solutions below

2
On BEST ANSWER

I think you may want to setup your hashtable like so...

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

foreach($item in $test.GetEnumerator()){
    echo $item.key
    echo $item.value
}
0
On

I agree with @dno and the comments. I have added to this with the output so you can see it working as explained.

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

foreach($item in $test.GetEnumerator()){
    $key = $item.key
    $value = $item.value
    Write-Output $key $value
}