PowerShell Hashtable Lookup
Hashtable lookup is reading a value from a hashtable by its key. A hashtable is a collection that pairs a name with a value.
Read a value with dot access
Put a dot and the key name after the hashtable name. This reads one value at a time.
$person = @{name = "Ana"; age = 31}
$person.name
$person.ageRead a value with bracket access
Bracket access does the same job as dot access. Put the key name in quotes inside square brackets.
$person = @{name = "Ana"; age = 31}
$person["name"]
$person["age"]Check whether a key exists
Contains tells you if a key is present. It gives True when the key exists and False when it does not.
$person = @{name = "Ana"; age = 31}
$person.Contains("name")
$person.Contains("city")Example
$book = @{title = "Dune"; author = "Frank Herbert"; year = 1965}
$book.title
$book.author
$book.pages = 412
$book.pagesKey points
- Hashtable: a collection that pairs a name with a value.
- Key: the name you use to find a value in a hashtable.
- Dot access reads a value with a dot and the key name.
- Bracket access reads a value with the key name in square brackets.
- Contains checks whether a key exists and gives True or False.
In this example, a hashtable holds a book title, an author, and a year. Dot access reads the title and the author. A new key is then added for the page count, and dot access reads it back.
Note
Never print a whole plain hashtable or list its keys, because the order changes each run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which code reads the age value from a hashtable named $person?