PowerShell: How Pipe Works
Example of Pipe
You can send one command's output to another command's input.
This is called piping.
you write it as: command1 | command2 | command3
.
# list current dir, sort it dir | sort # list, sort, show first 5 elements dir | sort | select -first 5
# move jpg files to another dir dir -file *jpg | move ~/Pictures/
# filter out bot access from web log, save to new file Get-Content weblog | Select-String -notmatch "Googlebot" | Out-File path -width 111222333 -NoNewLine weblog2
How Pipe Works
- The output of PowerShell commands are dotnet objects. They display on screen as formatted text representation. Unlike unix shells, it is not passing text streams.
- Each dotnet object has a type, and members. Member means property or method. [see Object Type, Properties, Methods]
- Output of a command may be a collection object. (collection is a type, and is like a list, each element is a object.) e.g. output of
dir
. - Objects in collection may be different types. e.g. output of
dir
may be a singleSystem.IO.FileInfo
orSystem.IO.DirectoryInfo
, or a collection of them. - Pipeline output is passed as arguments into one of the paramater of the receiving command.
The command's doc (
help cmd
) specifies which paramaters (if any) can accept argument from pipeline. When more than one paramater can 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.) - When output is a collection, it is piped into receiving command element at a time, in order.
(Note: it is not passing the whole collection as one single value) For example,
dir | select -First 5
. - If a command receives collection type argument from its paramater and not via pipeline, it is received as one single object.
For example,
select -InputObject (dir) -First 5
no work.
See also: Object Type, Properties, Methods