Arrays
This section covers array creation, access, iteration, add/remove/modify, filtering/sorting, pipeline interaction, multidimensional and jagged arrays, as well as performance and practice recommendations in PowerShell.
1. Creating Arrays
- Comma-separated literals:powershell
$nums = 1,2,3,4 $mix = 1, 'a', (Get-Date) $empty = @() # Empty array - Strongly-typed arrays (constrain element types):powershell
$ints = [int[]](1,2,3) $bytes = [byte[]](0x01,0xFF) # Create empty array first then convert type: $ints = [int[]]@() - Expansion operations:powershell
$a = 1,2; $b = 3,4 $c = $a + $b # Result is new array 1,2,3,4 (note: arrays are fixed-length, + creates new array)
2. Access and Slicing
- Indexing (supports negative indices, ranges):powershell
$nums[0] # First element $nums[-1] # Last element $nums[1..3] # Subarray from index 1 to 3 $nums[0,2,4] # Select multiple discrete indices $nums[($nums.Length-1)..0] # Reverse
3. Iteration (Enumeration)
powershell
foreach ($n in $nums) { $n * 2 }
$nums | ForEach-Object { $_ * 2 }- From PowerShell 3+, arrays provide .ForEach()/.Where() extension methods (convenient and efficient):powershell
$nums.Where({ $_ -gt 10 }, 'First', 3) # Find first 3 elements > 10 $nums.ForEach({ $_ * 2 }) # Map
4. Add/Remove/Modify (Mutability and Alternatives)
- Arrays are "fixed-length" collections, using += or + to append elements creates a new array, frequent operations have performance overhead:powershell
$nums += 5 # New array (original array not resized in-place) $nums = $nums + 6 - Insert/Delete commonly use "slice concatenation" technique:powershell
# Insert 99 at index 2 $nums = $nums[0..1] + 99 + $nums[2..-1] # Delete element at index 3 $nums = $nums[0..2] + $nums[4..-1] - High-performance appending: Recommended to use generic List[T], then ToArray() at the endpowershell
$list = [System.Collections.Generic.List[int]]::new() $list.AddRange(1..10000) $list.Add(10001) $nums = $list.ToArray()
5. Filtering, Sorting, Deduplication
powershell
$nums | Where-Object { $_ -gt 3 } | Sort-Object -Descending
$nums | Sort-Object | Get-Unique # Note: Get-Unique requires "sorted" input
$nums -contains 3 # Whether contains value 3 (boolean)
5 -in $nums # Whether 5 is in array6. Other Common Operations
powershell
$nums.Length
$nums.Count
($nums -join ',') # Join into string
"1,2,3,4" -split ',' # Split into array
$a,$b,$c = 1,2,3 # Parallel unpacking7. Multidimensional and Jagged Arrays
- Multidimensional (matrix):powershell
$grid = New-Object 'object[,]' 2,3 $grid[0,1] = 'X' $grid[1,2] = 'Y' - Jagged (array of arrays):powershell
$jagged = @(@(1,2), @('a','b')) $jagged[0][1] # 2
8. Pipeline and Enumeration Behavior
- Most commands process array elements one by one:powershell
1,2,3 | ForEach-Object { $_ * 10 } - Unary comma prevents expansion (wraps single object into array of length 1):powershell
,(Get-Item .\file.txt) | Measure-Object
9. Practical Examples
- Find top 5 largest files in current directory:powershell
Get-ChildItem -File | Sort-Object Length -Descending | Select-Object -First 5 Name, Length - Group even and odd numbers (PowerShell 3+):powershell
$nums = 1..20 $even = $nums.Where({ $_ % 2 -eq 0 }) $odd = $nums.Where({ $_ % 2 -ne 0 })
10. Performance and Recommendations
- For frequent appending/insertion, use List[T] or queue/stack; convert back to array at the end.
- Use Sort-Object for stable sorting (stable by default).
- When processing object array properties, combine Select-Object/Where-Object for best results.