What is an Array?
An array in PowerShell is a collection of items stored in a single variable. Each item, or element, can be of any type: strings, integers, objects, or even other arrays. Unlike some other languages, PowerShell arrays are heterogeneous, meaning they can store different types of elements within the same array.
# Example of a heterogeneous array
$array = @("String", 123, $true, (Get-Date))
$array
# Output
String
123
True
Wednesday, 4 December 2024 09:23:04
Creating Arrays
# Initialize an empty array
$emptyArray = @()
# Array with elements
$numbers = @(1, 2, 3, 4, 5)
Array Assignment Without @()
PowerShell automatically treats comma-separated values as an array.
$numbers = 1, 2, 3, 4, 5
Accessing and Manipulating Arrays
Each element in an array is accessed by its index, starting from zero.
# Accessing elements
$firstElement = $numbers[0]
$lastElement = $numbers[-1] # Negative indexing accesses from the end
# Modify an element
$numbers[1] = 10
# Add elements
$numbers += 6
Removing Elements
PowerShell lacks a direct Remove()
method for arrays, but you can filter out elements using a pipeline.
# Remove an element
$numbers = $numbers | Where-Object { $_ -ne 10 }
Array Methods and Properties
Arrays in PowerShell have several methods and properties inherited from the .NET framework.
Count Property
Get the number of elements in an array.
$numbers.Count
Contains() Method
Check if an array contains a specific value.
$numbers.Contains(5)
Sort and Reverse Arrays
Manipulate the order of elements.
# Sort
$sortedArray = $numbers | Sort-Object
# Reverse
$reversedArray = $numbers | ForEach-Object { $_ } | Sort-Object -Descending
Multidimensional and Jagged Arrays
A multidimensional array is a grid-like structure.
# Create a 2x2 array - Multidimensional
$matrix = @(@(1, 2), @(3, 4))
$matrix[0][1] # Access second element of the first array
# Jagged array - arrays of arrays with varying lengths
$jagged = @(@(1, 2), @(3, 4, 5))