HOWTO · PowerShell

How to Create an Array, Hash Table, and Dictionary in PowerShell

Learn how to create and use arrays, hash tables, and ordered dictionaries in PowerShell with this comprehensive guide. Understand the key differences, how to access, add, and remove items, and when to use each data structure. Includes practical examples, real-world use cases, and an FAQ section to help you master PowerShell scripting and data manipulation efficiently. Perfect for beginners and advanced users looking to enhance automation and data organization in PowerShell.

On this page

Choose an array (@()) for a sequence of values, a hash table (@{}) for key-value lookup, and an ordered dictionary ([ordered]@{}) when the order in which keys were added must be retained. The examples below are self-contained PowerShell snippets. No runtime observations are available for these examples, so no output is asserted.

Creating Arrays in PowerShell

An array stores multiple values in one variable. PowerShell array indexes start at zero, and -1 refers to the last element. @() explicitly collects results as an array, including when a command returns a single value. Run this example:

$items = @('apple', 'banana', 'cherry')
$items[0]
$items[-1]
$items += 'date'
$items = @($items | Where-Object { $_ -ne 'banana' })
$items -join ', '

The example reads the first and last values, appends one value, then assigns a filtered array that excludes banana. PowerShell arrays have fixed size; += creates a resulting array and assigns it back, so repeatedly appending to a large array can require repeated copying. For frequent additions and removals, a mutable collection such as System.Collections.Generic.List[object] may be a better fit. To inspect an array’s type, use $items.GetType().FullName; @() produces an Object[] for these string values.

Working with Hash Tables in PowerShell

A PowerShell hash table maps keys to values. Create one with @{}, read an entry with bracket notation, assign a key to add or replace an entry, and call .Remove() to delete one. Brackets work reliably for arbitrary key names; dot notation is convenient when a key is a simple property-like name, but can collide with built-in members such as Count.

$inventory = @{ Fruit = 'Apple'; Color = 'Red'; Count = 5 }
$inventory['Color']
$inventory['Shape'] = 'Round'
$inventory.Remove('Color')
$inventory.GetEnumerator() | Sort-Object Name | ForEach-Object {
    "{0}={1}" -f $_.Name, $_.Value
}

The last pipeline sorts the emitted entries by key for display. It does not reorder or replace the original hash table. PowerShell’s hashtable keys are case-insensitive by default; use a different collection when key comparison semantics need to differ.

Creating Ordered Dictionaries in PowerShell

The [ordered] literal creates an ordered dictionary and retains the order in which entries were inserted. Access and update entries with keys just as you would in a hash table. Insertion order is distinct from alphabetical sorting: the original order remains the insertion sequence unless you explicitly sort a separate result.

$settings = [ordered]@{ Name = 'Delft'; Region = 'South Holland'; Active = $true }
$settings['Region']
$settings['Timezone'] = 'Europe/Amsterdam'
$settings.GetEnumerator() | ForEach-Object {
    "{0}={1}" -f $_.Key, $_.Value
}

Hash Table vs. Ordered Dictionary: Key Differences

Feature Hash table Ordered dictionary
PowerShell literal @{} [ordered]@{}
Data model Keys map to values Keys map to values
Iteration order Do not rely on insertion order Preserves insertion order
Read or update an entry $table['key'] $dictionary['key']
Best fit Lookup by key when display order is unimportant Key-value data whose insertion order matters

A PowerShell hash table is not the same thing as every .NET dictionary type. System.Collections.Hashtable is a .NET type used by PowerShell’s @{} literal, while .NET also provides other dictionary implementations with their own ordering and comparison behavior. Choose based on the specific type and behavior your code needs. Avoid assuming either collection is faster without measuring the actual workload.

Practical Use Cases

Use an ordered dictionary for user or configuration fields when output should follow a chosen sequence. Use a hash table to count words by key. These examples show both tasks; the code is standalone and no output is claimed for it.

$user = [ordered]@{
    Name = 'John Doe'
    Email = 'johndoe@example.com'
    Role = 'Admin'
}
$user.GetEnumerator() | ForEach-Object { "{0}: {1}" -f $_.Key, $_.Value }

$text = 'apple banana apple orange apple banana'
$wordCount = @{}
$text.Split() | ForEach-Object {
    if ($wordCount.ContainsKey($_)) {
        $wordCount[$_] += 1
    } else {
        $wordCount[$_] = 1
    }
}
$wordCount.GetEnumerator() | Sort-Object Name | ForEach-Object {
    "{0}: {1}" -f $_.Name, $_.Value
}

Conclusion

Use arrays for ordered sequences that you process by position, hash tables for key-based lookup, and ordered dictionaries when the insertion sequence is part of the data you present. Remember that array += assigns a new array, filtering returns a result to assign, and sorting a hash table’s enumerated entries changes the displayed result rather than the table itself.

Frequently Asked Questions (FAQ)

What is the difference between a hash table and a dictionary in PowerShell?

In everyday PowerShell usage, “dictionary” can describe a general key-value structure, and @{} creates a PowerShell hash table backed by the .NET System.Collections.Hashtable type. The .NET class library also has distinct dictionary types, so check the concrete type when APIs require a particular implementation.

How do I add or remove items from a PowerShell array?

Append with $array += 'newItem', then assign the result back to the variable. To remove matching values, filter and assign the result, for example $array = @($array | Where-Object { $_ -ne 'itemToRemove' }). These operations produce an array result; they do not resize the existing array in place.

Can I sort a hash table in PowerShell?

Sort its entries for display with $hash.GetEnumerator() | Sort-Object Name. This returns sorted entries and leaves $hash unchanged. Use [ordered]@{} when you need insertion order; it preserves the order in which entries were added, rather than sorting keys alphabetically.