Arrays Are like In-Memory Database Tables
Arrays are fundamental to PowerShell scripting. They allow you to store and manipulate collections of objects, making them essential for handling data in scripts. Think of arrays as in-memory database tables where each element is a row, and you can perform operations like filtering, sorting, and slicing.
1. What is an Array?
An array is a collection of objects. Unlike a scalar (a single object), an array can hold zero, one, or many objects. Arrays are sometimes called collections or lists.
2. Creating Arrays
Empty Array
To create an empty array:
Array with Elements
To create an array with elements, separate them with commas:
The @()
syntax ensures the variable is treated as an array, even if it contains only one element.
Implicit Array Creation
You can also create arrays without explicitly using @()
:
Range Operator
To create an array with a sequence of numbers:
Single-Element Array
To create an array with a single element:
Appending to an Array
To add elements to an existing array:
3. Accessing Array Elements
Counting Elements
To get the number of elements in an array:
Displaying Elements
To display all elements:
To display elements as a single string (space-separated):
To display elements as a comma-separated string:
Accessing Specific Elements
Array elements are indexed starting from 0
. Use square brackets []
to access elements:
Slicing Arrays
To retrieve a range of elements:
To extract specific elements:
Assigning Elements to Variables
To extract elements and assign them to variables:
4. Nested Arrays (Array of Arrays)
A nested array is an array that contains other arrays. This is useful for representing multi-dimensional data.
Creating Nested Arrays
Accessing Nested Array Elements
To access elements in a nested array:
5. Manipulating Arrays
Filtering Arrays
Use Where-Object
to filter arrays:
Sorting Arrays
Use Sort-Object
to sort arrays:
Adding and Removing Elements
Add: Use
+=
to append elements.Remove: Use
Where-Object
to exclude elements.
Example:
6. Advanced Array Features
Multidimensional Arrays
PowerShell doesn’t natively support multidimensional arrays, but you can simulate them using nested arrays:
Array Slicing with Ranges
Use ranges to slice arrays dynamically:
Output Field Separator ($OFS
)
The $OFS
variable controls the separator used when converting arrays to strings:
Last updated