Tiamo Idzenga
Tiamo Idzenga

Reputation: 1156

How to query nested properties of a Hashtable?

Imagine you have a Hashtable such as this:

$ht = @{
    Foo = @{
        Bar = "Baz"
        Qux = "Quux"
    }
    Quuz = @{
        Bar = "Corge"
        Qux = "Grault"
    }
}

Imagine that you want to get an array of each of the Hashtable's Bar property. How would you go about this? Is this possible without iterating?

This is what I came up with:

$arr = @()

foreach ($i in $ht.GetEnumerator()) {
    foreach ($n in $i.Name) {
        $arr += $ht.$n.Bar
    }
}
PS C:> echo $arr
Corge
Baz

Really, though, it seems to me it should be simpler. Perhaps using PSCustomObject & Select-Object? I'm open to any solutions.

Upvotes: 2

Views: 429

Answers (2)

Dr. C.
Dr. C.

Reputation: 106

Like this?


$myDict = @{
    key1 = @{   key98 = "Hello"
                key99 = "Goodbye" } 
    key2 = 'value2' }

$myDict.key1

Name                           Value                                           
----                           -----                                           
key99                          Goodbye                                         
key98                          Hello                                           

PS E:\> $myDict.key2
value2

PS E:\> $myDict.key1.key98
Hello

PS E:\> $myDict.key1.key99
Goodbye

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

PowerShell (since version 3.0) supports member enumeration, allowing us to simplify your loop to the following statment:

$arr = $ht.Values.Bar

Since the collection stored in Hashtable.Values has no Bar property, PowerShell enumerates it and attempts to resolve the member reference against the individual items, much like if you had done:

$ht.Values |ForEach-Object { $_.Bar } 
# or
$ht.Values |ForEach-Object Bar 
# or
$ht.Values |Select -Expand Bar

Upvotes: 2

Related Questions