Powershell assignment makes no sense

Read the code, guess what it prints, run the code and let us know …

$dict1 = @{
    'Key1' = 5
    'Key2' = 15
    'Key3' = 30
}

$dict2 = @{
    'Key1' = 8
    'Key2' = 14
    'Key3' = 29
}

$array = @($dict1, $dict2)
Write-Host "We have $($array.Count) items in the array"

$result = $array | Where-Object Key1 -eq 5
Write-Host "And now have $($result.Count)"

And yes, it likely is documented. Somewhere. Maybe.

What’s your question? Or what’s your issue with it? Or what would you have expected?

It is an array with 2 hashtables in it. :man_shrugging:t3:

Here you filter for all hashtables where key Key1 has the value 5. It is just 1 of the hashtables. And that’s a hashtable with 3 hashsets in it. :man_shrugging:t3:

2 Likes

Yep Olaf is right here. I think I understand your confusion though. You’re expecting the result to be 1 yes?

What’s happening is essentially nested objects. When you do the $array assignment, you’re creating two objects in the array, which each have ‘sub objects’, if you will. You then are setting $result equal to a filter, which actually happens to be only 1 object, which has 3-sub objects in it. Because of this, it’s returning that top level object which has 3 objects. If you want to ‘force’ it to a single object, you can try casting the variable to an array:

[Array]$result = $array | Where-Object Key1 -eq 5
$result.count

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.