3

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!

1
  • Your $test value is syntactically invalid. You probably meant to use a hashtable, which is created with @{ ... }, not @(...). Commented Sep 28, 2020 at 13:14

2 Answers 2

6

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

As an aside: While Write-Output, whose built-in alias is echo, is the right tool for outputting data, you typically don't need to use it explicitly, because PowerShell implicitly outputs (to the success data stream) any expression or command that isn't captured or redirected; e.g., just $foo by itself has the same effect as Write-Output $foo / echo $foo. While there is no harm in using Write-Output, consider showcasing PowerShell's implicit output feature instead (possibly with an explanatory comment), so as to promote PowerShell-idiomatic solutions.
Glad to hear we agree, but I suggest you actually update your answer with this information, for the benefit of future readers. Once you have done so, you can flag my first and this comment as "No longer needed" (or ping me, so I can remove them myself).
2

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
}

Comments

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.