Pipeline
PowerShell's pipeline passes "objects" between commands rather than plain text, making data processing more robust and efficient.
1. Core Concepts
- The pipe operator
|passes output objects from the previous command one by one to the next command's "parameter binding" logic. - Binding methods:
- ByValue: When the input object type matches the target parameter type, bind directly.
- ByPropertyName: When the input object has a property with the same name as the parameter, bind it.
- Common processors:
Where-Object(filter),Select-Object(project/select columns),Sort-Object(sort),Group-Object(group),Measure-Object(aggregate).
2. Example: Top N Largest Processes
3. ByPropertyName Example
4. Flow Control and Expansion
- Value expansion:
Select-Object -ExpandPropertysends the property value itself into the pipeline - Connect multiple streams:
Write-Output(success output),Write-Error(error logging), etc. - End aggregation:
ForEach-Object -End { ... }performs summary when stream ends
5. Performance Points
- Try to place filtering (Where-Object) early in execution to reduce subsequent data volume.
- Project necessary fields before large data sorting and deduplication.
- Prefer using .Where()/.ForEach() extension methods (PowerShell 3+) to reduce script overhead:
6. Errors and Interruption
- Command failures don't terminate the pipeline by default, can force termination with
-ErrorAction Stopor$ErrorActionPreference='Stop'. - Catch and continue:
7. Common Patterns
- Grouped aggregation report:
- Conditional branch processing:
8. Summary
- Pipeline passing objects reduces the fragility of parsing/concatenating text.
- Combining ByValue/ByPropertyName, choosing appropriate processors and extension methods, can write efficient and readable one-liner streaming scripts.