How to Pipe or Redirect Output to Another Command
Introduction
In PowerShell, the pipe is a way to take the output of one command and pipe or redirect it into another command. This is similar to the concept of input/output (I/O) redirection in Unix and Linux. The pipe character is the vertical bar or |
symbol located on your keyboard above the backslash character.
Examples
For example, you can use the Get-Process cmdlet to get a list of all running processes on a computer. But what if you only want to see a list of processes that are using more than 500 MB of memory? You could use the Where-Object
cmdlet to filter the output of Get-Process like this:
Get-Process | Where-Object {$_.WorkingSet -gt 524288000}
This command would get a list of all processes and then pipe that output into Where-Object
, which would filter the output based on the condition that WorkingSet is greater than 524288000 (500 MB).
Below is the output if we execute above script.
![Get Processes Greater Than 500 MB](https://www.byteinthesky.com/powershell/how-to-pipe-output-to-another-command/Get%20Processes%20Greater%20Than%20500%20MB.png)
You can also use PowerShell pipes with external commands. For example, let’s say you want to use the findstr
command to search for a string in a file. But instead of searching through every file in a directory, you just want to search through files with a .ps1
extension.
You can use PowerShell’s Get-ChildItem
cmdlet to get a list of all .ps1
files in a directory and then pipe that output into findstr
like this:
Get-ChildItem *.ps1 | findstr "test"
This command would first get a list of all .ps1
files and then pipe that output into findstr
, which would search for the specified string.
Below is the output if we execute above script.
![Get All PowerShell Files whose name contain test](https://www.byteinthesky.com/powershell/how-to-pipe-output-to-another-command/Get%20All%20PowerShell%20Files%20whose%20name%20contain%20test.png)
Conclusion
Piping is a powerful way to take the output of one command and use it as input for another command. In PowerShell, the pipe character is |
. This article showed how you can use pipes with both built-in PowerShell cmdlets and external commands.