PowerShell Nested Data
Nested data is data stored inside other data. A hashtable can hold another hashtable, and it can also hold an array.
Read from a hashtable inside a hashtable
Chain the accesses from the outside in. First read the inner hashtable, then read its key.
$user = @{name = "Ana"; address = @{city = "Porto"; zip = "4000"}}
$user.address.city
$user.address.zipRead an item from an array inside a hashtable
Read the array with its key first, then pick an item by index. Index 0 is the first item.
$user = @{name = "Ana"; scores = @(90, 85, 95)}
$user.scores[0]
$user.scores[1]
$user.scores[-1]Read from hashtables inside an array
Pick a hashtable by its array index first, then read a key from it. Each hashtable keeps its own values.
$users = @(@{name = "Ana"; age = 31}, @{name = "Sam"; age = 28})
$users[0].name
$users[1].ageExample
$order = @{id = 101; customer = @{name = "Ana"; city = "Porto"}; items = @("book", "pen")}
$order.id
$order.customer.name
$order.customer.city
$order.items[0]
$order.items[1]Key points
- Nested: data stored inside other data.
- A hashtable value can be another hashtable.
- Read a nested value by chaining one access after another.
- A hashtable value can be an array, and you read its items by index.
- An array can hold hashtables, and you read their keys after the index.
In this example, an order hashtable holds an id, a customer hashtable, and an items array. Each line prints one single value from the nested data. The id, the customer name, the customer city, and both items are read one at a time.
Note
Always print a single property or item from nested data, never the whole nested object.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
For $user = @{address = @{city = "Porto"}}, which code prints Porto?