PowerShell: Pipe Output
You can send one command's output to another command's input.
This is called piping.
you write it as:
command1 | command2 | command3.
Here are some examples:
# list current dir, sort it dir | sort # list, sort, show first 5 elements dir | sort | select -first 5 # list, sort, select, then format for display dir | sort | select -first 5 | format-table name, length
# move jpg files to another dir Get-Item $home/Documents/*jpg | Move-Item -Destination $home/Pictures/
# filter out bot access from web log, save to new file get-content weblog.txt | select-string -notmatch "Googlebot" | out-file -Encoding utf8 -width 999000 weblog2.txt
How Pipe Works
- The output of PowerShell commands are .NET objects. They display on screen as formatted text representation. Unlike unix shells, it is not passing text streams.
- Each .NET object has a type, and members. “Member” means property or method. You can find the object type of command output by pipe it to
Get-Member. [see PowerShell: Object Type, Properties, Methods]
- Output of a command may be more than one object. For example, output of
- Objects in output may be different types. For example, output of
dirmay be files (type
System.IO.FileInfo) and directories (type
- Pipeline output is passed as arguments into one of the paramater of the receiving command. The command's doc (
help cmd) specifies which paramaters (in any) can accept argument from pipeline. When more than one paramater accept pipeline input, PowerShell makes a choice automatically based on the object type. User cannot chose which parameter to use for pipeline input. (unlike unix, the pipeline does not go thru stdout and stdin.)
- In a pipeline, when there's more than one object in output, it'll be fed into receiving command one at a time, in order. For example,
Get-ChildItem | Select-Object -First 5. (Note: it is not passing one single object of array) However, if a command receives collection argument from its paramater (not via pipeline), it is received as one single array object. For example,
Select-Object -InputObject (Get-ChildItem) -First 5doesn't work.
- Technically, only some commands work well together in a pipeline and in particular order. But in general, this is intuitive and never a question. In general, you can tell by the cmdlet name.
Get-nounXusually works with
somethig-nounX. Also, certain commands are almost always used with pipeline, such as
Select-Object(select items by known info, such as length, property type, values.) and
Where-Object(select items by arbitrary tests),
See also: PowerShell: Object Type, Properties, Methods