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:
- Strongly-typed arrays (constrain element types):
- Expansion operations:
2. Access and Slicing
- Indexing (supports negative indices, ranges):
3. Iteration (Enumeration)
- From PowerShell 3+, arrays provide .ForEach()/.Where() extension methods (convenient and efficient):
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:
- Insert/Delete commonly use "slice concatenation" technique:
- High-performance appending: Recommended to use generic List[T], then ToArray() at the end
5. Filtering, Sorting, Deduplication
6. Other Common Operations
7. Multidimensional and Jagged Arrays
- Multidimensional (matrix):
- Jagged (array of arrays):
8. Pipeline and Enumeration Behavior
- Most commands process array elements one by one:
- Unary comma prevents expansion (wraps single object into array of length 1):
9. Practical Examples
- Find top 5 largest files in current directory:
- Group even and odd numbers (PowerShell 3+):
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.