PowerShell Arrays: The Complete Guide to Collection Management
Understanding PowerShell Arrays
Arrays are fundamental data structures that store collections of items in PowerShell. They can hold elements of any type and are essential for effective scripting and data management.
Array Declaration Basics
# Basic array with values
$numberArray = 22, 5, 10, 8, 12, 9, 80
# Empty array initialization
$emptyArray = @()
# Range operator array
$rangeArray = 100..110
# Mixed-type array
$mixedArray = "PowerShell", 42, (Get-Date), $true
Key Property:
$rangeArray.Length # Returns 11 (100-110 inclusive)
Accessing Array Elements
Index-Based Access
PowerShell arrays are zero-indexed:
$rangeArray[0] # Returns 100 (first element)
$rangeArray[-1] # Returns 110 (last element)
$rangeArray[2..5] # Returns 102,103,104,105 (range)
$rangeArray[0,3,6] # Returns 100,103,106 (specific indices)
Iterating Through Arrays
foreach ($number in $rangeArray) {
Write-Output "Processing: $number"
}
# Alternative with For loop
for ($i=0; $i -lt $rangeArray.Length; $i++) {
Write-Output "Index $i contains $($rangeArray[$i])"
}
Specialized Array Techniques
Strongly Typed Arrays
Enforce data type consistency:
[int[]]$intOnly = 1300, 22, 4578, 8000
[datetime[]]$dateArray = (Get-Date), "2023-01-01"
# This will throw an error:
$intOnly[0] = "string"
Practical AD Example
$adUsers = @()
$adUsers = Get-ADUser -Filter * -Properties Mail
foreach ($user in $adUsers) {
if ($user.Mail) {
Write-Output "Processing $($user.SamAccountName)"
}
}
Array Manipulation
Modifying Elements
# Update by index
$rangeArray[0] = 200
# Using SetValue method
$rangeArray.SetValue(201, 1)
Adding Elements
# Note: Creates new array (inefficient for large arrays)
$rangeArray += 500
# Better alternative for large arrays:
$list = [System.Collections.ArrayList]::new($rangeArray)
$list.Add(500) | Out-Null
Removing Elements
# Create new array without last element
$trimmedArray = $rangeArray[0..($rangeArray.Length-2)]
# Filter specific elements
$filteredArray = $rangeArray | Where-Object { $_ -gt 105 }
Clearing Arrays
$rangeArray = $null # Best performance
Remove-Variable rangeArray # Alternative method
Performance Considerations
- Array Addition:
+=
creates new arrays - useArrayList
for frequent modifications - Large Datasets: Consider
[System.Collections.Generic.List[object]]
for better performance - Memory Management: Explicitly clear large arrays when no longer needed
Pro Tip: For advanced scenarios, explore:
- Multidimensional arrays
- Jagged arrays (arrays of arrays)
[System.Collections.Specialized.CollectionsUtil]::CreateCaseInsensitiveHashtable()
Leave a comment