PowerShell: How Pipe Works
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 | ft name, length
# move jpg files to another dir Get-Item $home/Documents/*jpg | mv -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
gm). [see 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 (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.)
- 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. (Note: it is not passing one array) For example,
dir | select -First 5. However, if a command receives collection argument from its paramater (not via pipeline), it is received as one single array object. For example,
select -InputObject (dir) -First 5doesn't work.
See also: Object Type, Properties, Methods