MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Piping Output and Input

Xah Lee,

PowerShell lets you send one command's output to the next command's input, called piping. This is similar to the idea of nesting functions, but using a linear syntax.

For example, suppose you have function f, g, h, and you want to compute “h(g(f(x)))”. The nested syntax is inconvenient to use. With post-fix notation, for example used in bash, you can write it as: “x | f | g | h”. This is called a pipe, because it is analogous to water flowing thru pipes.

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
# list help topics with summary
Get-Help about* | Select-Object Name,Synopsis | Format-Table -Auto
# moving png image files to another dir 
Get-Item $HOME/Documents/*png | Move-Item -Destination $HOME/Pictures/
# filter out bot access from web log, save to file
get-content web-log.txt | 
select-string -notmatch "Googlebot" | 
out-file -Encoding utf8 -width 999000 web-log2.txt
# piping example on showing processes
Get-Process | Select-Object Name

Get-Process | Sort-Object ID -descending

Get-Process |
Where-Object { $_.Handles -ge 500 } |
Sort-Object Handles |
Format-Table Handles,Name,Description -Auto

Note that the output of PowerShell are .NET objects. They display on screen as formatted text representation. Unlike unix shells, it is not passing text streams.

# using get-member to see object's members
dir | get-member
blog comments powered by Disqus
2009-07