PowerShell/Arrays and Hash Tables - Wikiversity (2024)

This lesson introduces PowerShell arrays and hash tables.

Contents

  • 1 Objectives and Skills
  • 2 Readings
  • 3 Multimedia
  • 4 Examples
    • 4.1 Initializing an Array
    • 4.2 Checking the Size of an Array
    • 4.3 Accessing Array Elements
    • 4.4 Initializing an Empty Array
    • 4.5 Adding Elements to an Array
    • 4.6 Removing Elements from an Array
    • 4.7 Looping Through an Array Using a For Loop
    • 4.8 Looping Through an Array Using a ForEach Loop
    • 4.9 Multi-Dimensional Arrays
    • 4.10 Initializing a Hash Table
    • 4.11 Accessing Hash Table Items
    • 4.12 Initializing an Empty Hash Table
    • 4.13 Adding Items to a Hash Table
    • 4.14 Removing Items from a Hash Table
    • 4.15 Looping Through a Hash Table Using ForEach
    • 4.16 Format-Table
    • 4.17 Format-List
  • 5 Activities
  • 6 Lesson Summary
  • 7 Key Terms
  • 8 Review Questions
  • 9 Assessments
  • 10 See Also
  • 11 References

Objectives and Skills[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic array and hash table concepts
  • Create PowerShell scripts that use arrays.
  • Create PowerShell scripts that use hash tables.

Readings[edit | edit source]

  1. Wikipedia: Array data type
  2. Wikipedia: Associative array
  3. BonusBits: Mastering PowerShell Chapter 4 - Arrays and Hashtables

Multimedia[edit | edit source]

  1. YouTube: Arrays

Examples[edit | edit source]

Initializing an Array[edit | edit source]

$array=@(1,2,3,5,6,7,8);

Checking the Size of an Array[edit | edit source]

$array.Length

Accessing Array Elements[edit | edit source]

$array[0] + $array[1] + $array[2]

Initializing an Empty Array[edit | edit source]

$array = @()

Adding Elements to an Array[edit | edit source]

$array += 1$array += 2$array += 3

Removing Elements from an Array[edit | edit source]

To remove the elements which are not required in an array, use the below command. This stores only the sub-arrays mentioned here.

$array = @($array[0], $array[2])

Looping Through an Array Using a For Loop[edit | edit source]

for($i = 0; $i -lt $array.Length; $i++){ $array[$i]}

Looping Through an Array Using a ForEach Loop[edit | edit source]

foreach($element in $array){ $element}

Multi-Dimensional Arrays[edit | edit source]

$array = @(1, 2, 3), @(4, 5, 6), @(7, 8, 9)$array[0] # 1 # 2 # 3$array[0][0] # 1$array[2][2] # 9

Initializing a Hash Table[edit | edit source]

$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'}

Accessing Hash Table Items[edit | edit source]

$pets.Cat  # Frisky$pets.Dog # Spot$pets.Fish # Nimo$pets.Hamster # Whiskers

Initializing an Empty Hash Table[edit | edit source]

$pets = @{}

Adding Items to a Hash Table[edit | edit source]

Either:

$pets.Add('Cat', 'Frisky')$pets.Add('Dog', 'Spot')$pets.Add('Fish', 'Nimo')$pets.Add('Hamster', 'Whiskers')

or:

$pets.Cat = 'Frisky'$pets.Dog = 'Spot'$pets.Fish = 'Nimo'$pets.Hamster = 'Whiskers'

Removing Items from a Hash Table[edit | edit source]

$pets.Remove('Hamster')

Looping Through a Hash Table Using ForEach[edit | edit source]

foreach($pet in $pets.keys){ $pet # Print each Key $pets.$pet # Print value of each Key}

Format-Table[edit | edit source]

The Format-Table cmdlet formats hash table output as a table.[1]

$pets | Format-Table

Format-List[edit | edit source]

The Format-List cmdlet formats hash table output as a list of separate key-value pairs.[2]

$pets | Format-List

Activities[edit | edit source]

  1. Review Microsoft TechNet: about_Arrays. Create a script that initializes an array with the names of all of the members of your family. Use Sort-Object to sort and display the names.
  2. Review Microsoft TechNet: about_Arrays. Create a script that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a for or while loop to store each score in an array. Finally, use a for or foreach loop to calculate and display the average for the entered scores.
  3. Review Microsoft TechNet: Working with Hash Tables Create a script that initializes a hash table with the names of all of the members of your family. Use Sort-Object and Format-Table to sort and display the names.
  4. As above, create a script that uses a hash table to hold the names of all of the members of your family and use Sort-Object to sort and display the names. This time, start by initializing an empty hash table, and add each name to the hash table as it is entered by the user. Use Sort-Object and Format-List to sort and display the names.
  5. Review Microsoft TechNet: about_Hash_Tables. Create a script that asks the user to enter their name, address, city, state, and postal code. Store each entry as an item in a hash table. Display the name and address information as you would for a printed mailing address.

Lesson Summary[edit | edit source]

  • An array is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.[3]
  • Arrays are distinguished from lists in that arrays allow random access, while lists only allow sequential access. This feature allows a single iterative statement to process arbitrarily many elements of an array variable.[4]
  • An index is a value, typically a numeric integer, used to identify and reference an array element.[5]
  • Array indexes start at either zero or one, depending on the programming language, and correspondingly end at either the number of elements minus one [0..n-1] or at the number of elements [1..n].[6] PowerShell arrays are zero-based.
  • The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type.[7]
  • Dynamic arrays are resizable and may be expanded at any time after creation, without changing the values of the current elements.[8]
  • Index checking means that, in all expressions indexing an array, the index value is checked against the bounds of the array (which were established when the array was defined), and if the index is out-of-bounds, further execution is suspended via some sort of error.[9]
  • A hash table is a data structure used to implement an associative array, a structure that can map keys to values.[10]
  • A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.[11]
  • An associative array is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.[12]
  • PowerShell arrays are initialized using @(value, value) syntax.[13]
  • PowerShell array elements are accessed using $array[element] syntax.[14]
  • An empty PowerShell array is created using @().[15]
  • PowerShell array elements are added using $array += element syntax.[16]
  • PowerShell array elements are removed using $array = $array[sub..set] + $array[sub..set] syntax.[17]
  • PowerShell multi-dimensional array elements are accessed using $array[element][element] syntax.[18]
  • PowerShell hash tables are initialized using @{key = value; key = value} syntax.[19]
  • Hash table values are accessed using $table.key syntax.[20]
  • An empty PowerShell hash table is created using @{}.[21]
  • PowerShell hash table values are added using $table.Add(key, value) syntax or $table.key = value syntax.[22]
  • PowerShell hash table values are removed using $table.Remove(key) syntax.[23]
  • The Format-Table cmdlet formats hash table output as a table.[24]
  • The Format-List cmdlet formats hash table output as a list of separate key-value pairs.[25]

Key Terms[edit | edit source]

array
A data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.[26]
associative array
An abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.[27]
hash table
A data structure used to implement an associative array, a structure that can map keys to values.[28]
index
A value, typically a numeric integer, used to identify and reference an array element.[29]
key
A data element which allows one to find an associated data value or values by using a database index, hash table or memory location.[30]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.

Click on a question to see the answer.

1.An array is a _____ that is meant to _____.

An array is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.

2.Arrays are distinguished from lists in that _____.

Arrays are distinguished from lists in that arrays allow random access, while lists only allow sequential access. This feature allows a single iterative statement to process arbitrarily many elements of an array variable.

3.An index is _____.

An index is a value, typically a numeric integer, used to identify and reference an array element.

4.Array indexes start at _____, and correspondingly end at _____. PowerShell arrays are _____-based.

Array indexes start at either zero or one, depending on the programming language, and correspondingly end at either the number of elements minus one [0..n-1] or at the number of elements [1..n]. PowerShell arrays are zero-based.

5.The number of indices needed to specify an element is called the _____.

The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type.

6.Dynamic arrays are _____.

Dynamic arrays are resizable and may be expanded at any time after creation, without changing the values of the current elements.

7.Index checking means that _____.

Index checking means that, in all expressions indexing an array, the index value is checked against the bounds of the array (which were established when the array was defined), and if the index is out-of-bounds, further execution is suspended via some sort of error.

8.A hash table is _____.

A hash table is a data structure used to implement an associative array, a structure that can map keys to values.

9.A hash table uses _____ to compute an index into an array of buckets or slots, from which the correct value can be found.

A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

10.An associative array is _____.

An associative array is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.

11.PowerShell arrays are initialized using _____ syntax.

PowerShell arrays are initialized using @(value, value) syntax.

12.PowerShell array elements are accessed using _____ syntax.

PowerShell array elements are accessed using $array[element] syntax.

13.An empty PowerShell array is created using _____.

An empty PowerShell array is created using @().

14.PowerShell array elements are added using _____ syntax.

PowerShell array elements are added using $array += element syntax.

15.PowerShell array elements are removed using _____ syntax.

PowerShell array elements are removed using $array = $array[sub..set] + $array[sub..set] syntax.

16.PowerShell multi-dimensional array elements are accessed using _____ syntax.

PowerShell multi-dimensional array elements are accessed using $array[element][element] syntax.

17.PowerShell hash tables are initialized using _____ syntax.

PowerShell hash tables are initialized using @{key = value; key = value} syntax.

18.Hash table values are accessed using _____ syntax.

Hash table values are accessed using $table.key syntax.

19.An empty PowerShell hash table is created using _____.

An empty PowerShell hash table is created using @{}.

20.PowerShell hash table values are added using _____ syntax.

PowerShell hash table values are added using $table.Add(key, value) syntax or $table.key = value syntax.

21.PowerShell hash table values are removed using _____ syntax.

PowerShell hash table values are removed using $table.Remove(key) syntax.

22.The Format-Table cmdlet _____.

The Format-Table cmdlet formats hash table output as a table.

23.The Format-List cmdlet _____.

The Format-List cmdlet formats hash table output as a list of separate key-value pairs.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

  1. Microsoft TechNet: Format-Table
  2. Microsoft TechNet: Format-List
  3. Wikipedia: Array data type
  4. Wikipedia: Array data type
  5. Wikipedia: Array data type
  6. Wikipedia: Array data type
  7. Wikipedia: Array data type
  8. Wikipedia: Array data type
  9. Wikipedia: Bounds checking
  10. Wikipedia: Hash table
  11. Wikipedia: Hash table
  12. Wikipedia: Associative array
  13. Microsoft TechNet: about_Arrays
  14. Microsoft TechNet: about_Arrays
  15. Microsoft TechNet: about_Arrays
  16. Microsoft TechNet: about_Arrays
  17. Microsoft TechNet: about_Arrays
  18. SS64: Arrays
  19. Microsoft TechNet: about_Hash_Tables
  20. Microsoft TechNet: about_Hash_Tables
  21. Microsoft TechNet: about_Hash_Tables
  22. Microsoft TechNet: about_Hash_Tables
  23. Microsoft TechNet: about_Hash_Tables
  24. Microsoft TechNet: Format-Table
  25. Microsoft TechNet: Format-List
  26. Wikipedia: Array data type
  27. Wikipedia: Associative array
  28. Wikipedia: Hash table
  29. Wikipedia: Array data type
  30. Wikipedia: Key
PowerShell/Arrays and Hash Tables - Wikiversity (2024)

FAQs

What is the difference between hash table and array in PowerShell? ›

Like many other scripting and programming languages, Windows PowerShell allows you to work with arrays and hash tables. An array is a collection of values that can be stored in a single object. A hash table is also known as an associative array and is a dictionary that stores a set of key-value pairs.

What is the difference between hash table and array? ›

Arrays are useful when you need to store a fixed number of elements of the same type, access them by index, and iterate over them in order. Hash tables are ideal when you need to store variable number of elements of different types, access them by key, and perform frequent insertions and deletions.

How do you display Hashtable content in PowerShell? ›

To display a hashtable that's saved in a variable, type the variable name. By default, a hashtables is displayed as a table with one column for keys and one for values. hashtables have Keys and Values properties. Use dot notation to display all the keys or all the values.

What is @{} in PowerShell? ›

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array").

Why use a hash table instead of an array? ›

Hash Tables vs Arrays

Hash tables tend to be faster when it comes to searching for items. In arrays, you have to loop over all items before you find what you are looking for while in a hash table you go directly to the location of the item.

When should you use hash tables over an array? ›

Arrays are great for scenarios where fast random access and fixed-size storage are required, while hash tables are more suitable for scenarios where fast access to elements by key is required and memory usage is not as much of a concern.

What is the disadvantage of array over hash table? ›

Space efficiency: Unlike arrays or linked lists, which consume space proportionally to their size, hash tables only utilize space proportional to the number of elements they contain.

Are hash tables always arrays? ›

Hash tables are frequently (even typically) implemented using a combination of an array and a hashing function. You will remember that arrays are random access data structures which are capable of retrieving stored elements in constant (O(1)) time. You can think of arrays as having [index, value] pairs.

Why are hash tables favored over arrays or linked lists? ›

Hash tables are easy to use. Hash tables offer a high-speed data retrieval and manipulation. Fast lookup: Hashes provide fast lookup times for elements, often in constant time O(1), because they use a hash function to map keys to array indices. This makes them ideal for applications that require quick access to data.

How to convert string to hashtable in PowerShell? ›

The ConvertFrom-StringData cmdlet converts the value in the $Here variable to a hash table. $Here = @' Msg1 = The string parameter is required. Msg2 = Credentials are required for this command.

How to get value from Hashtable in PowerShell? ›

For example, if your Hashtable is named $hash and you want to retrieve the value associated with the key “key1”, you can use $hash[“key1”]. This will return the corresponding value.

What is an array in PowerShell? ›

A PowerShell array holds a list of data items. The data elements of a PowerShell array need not be of the same type, unless the data type is declared (strongly typed).

What is hash table in PowerShell? ›

A hashtable is a data structure, much like an array, except you store each value (object) using a key. It's a basic key/value store. First, we create an empty hashtable. PowerShell Copy. $ageList = @{}

How do I create a hash table in PowerShell? ›

Create a Hash table and immediately populate it with some values: $array_name = @{key1 = item1; key2 = item2;...} Notice that placing quotes around the key is optional (unless the key contains spaces). Each key/value pair must either be placed on a separate line or separated with a semicolon delimiter.

How do you declare an array in PowerShell? ›

Creating an Array

Separating items by commas ( , ) is the simplest way to create an array in PowerShell. Alternatively, the array subexpression operator @( ) can be used. Anything placed within the parentheses is treated as an item of the array.

What is the use of hash table in PowerShell? ›

Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys.

Is a hash table an array? ›

In computing, a hash table, also known as a hash map or a hash set, is a data structure that implements an associative array, also called a dictionary, which is an abstract data type that maps keys to values.

What is the difference between HashSet and HashTable in PowerShell? ›

A HashSet is an implementation of a set - a collection of unique keys. HashMap and HashTable are both implementations of a Map - a collection of key value pairs where the keys are unique (kind of like a lookup table). HashTable is thread safe, but HashMap is not. HashTable does not allow a null key, but HashMap does.

Is a hash table an array or a linked list? ›

A hash table is different from binary trees and linked lists in the sense that it is implemented with an array. It stores data as key-value pairs. Each data value in a hash table has a key or index that is produced using a technique known as hashing.

Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 6093

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.