PowerShell/Arrays and Hash Tables
Appearance
This lesson introduces PowerShell arrays and hash tables.
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]- Wikipedia: Array data type
- Wikipedia: Associative array
- BonusBits: Mastering PowerShell Chapter 4 - Arrays and Hashtables
Multimedia
[edit | edit source]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]- 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.
- 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.
- 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.
- 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.
- 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]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]- Flashcards: Quizlet: Windows PowerShell - Arrays and Hash Tables
- Quiz: Quizlet: Windows PowerShell - Arrays and Hash Tables
See Also
[edit | edit source]References
[edit | edit source]- ↑ Microsoft TechNet: Format-Table
- ↑ Microsoft TechNet: Format-List
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Bounds checking
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Associative array
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ SS64: Arrays
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: Format-Table
- ↑ Microsoft TechNet: Format-List
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Associative array
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Key