Search code examples
powershellpowershell-2.0powershell-3.0powercli

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


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!


Solution

  • 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
    }