How to Use Pipe Operator in PowerShell: Simple Guide
In PowerShell, the
| pipe operator passes the output of one command as input to another command. It helps chain commands together to perform complex tasks step-by-step.Syntax
The pipe operator | connects commands by sending the output of the command on the left as input to the command on the right.
Syntax parts:
Command1: Produces output.|: The pipe operator.Command2: Receives input from Command1.
powershell
Command1 | Command2
Example
This example lists all running processes and then filters to show only those with names containing "powershell".
powershell
Get-Process | Where-Object { $_.Name -like '*powershell*' }Output
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
123 10 15000 20000 0.03 1234 1 powershell
110 8 14000 18000 0.01 5678 1 powershell_ise
Common Pitfalls
Common mistakes when using the pipe operator include:
- Trying to pipe commands that do not output objects or compatible data.
- Using commands that expect parameters instead of pipeline input.
- Not using script blocks
{ }when filtering withWhere-Object.
Example of a wrong and right way:
powershell
# Wrong: Trying to pipe string output directly to a parameter "text" | Select-String -Pattern "t" # Right: Use pipeline input properly with commands that accept it Get-Content file.txt | Select-String -Pattern "text"
Quick Reference
| Operator | Description | Example |
|---|---|---|
| | | Pass output of one command as input to another | Get-Process | Where-Object { $_.CPU -gt 10 } |
| | Select-Object | Select specific properties from objects | Get-Process | Select-Object Name, Id |
| | Sort-Object | Sort objects by property | Get-Process | Sort-Object CPU -Descending |
| | Format-Table | Format output as a table | Get-Process | Format-Table Name, CPU |
Key Takeaways
Use the pipe operator
| to send output from one command to another in PowerShell.Commands in the pipeline work with objects, making chaining powerful and flexible.
Always ensure the receiving command accepts pipeline input to avoid errors.
Use script blocks
{ } with Where-Object to filter pipeline data.The pipe operator helps build clear, readable, and efficient scripts.