Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


March 2008

PowerShell 101, Lesson 2

How to create pipelines and manage output
RSS
Subscribe to Windows IT Pro | See More Systems Administration Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!
SideBar    How to Handle Long PowerShell Statements

In this case, PowerShell displays the output from this command in a table, as shown in Figure 4. If you don’t want the output in this default format, you can pipe the statement output to a format cmdlet. PowerShell supports four cmdlets that format output: The Format-

  • Table cmdlet displays data in a table (Figure 4). This is the default format for most cmdlets, so you often don’t need to specify it.
  • The Format-List cmdlet displays data in a list.
  • The Format-Wide cmdlet displays data in a wide table that includes only one property value for each item.
  • The Format-Custom cmdlet displays data in a custom format, based on stored configuration information in a .ps1xml format file. You can use the Update- FormatData cmdlet to update a format file. (A discussion of the Update-Format- Data cmdlet and format files is beyond the scope of these lessons. See Power- Shell’s “Update-FormatData” Help file for more information.)

To change the format of the output from the preceding statement, you can pipe it to the Format-List cmdlet:

Get-Process powershell |
Format-List

Now your results will be similar to those in Figure 5. Notice that the list format displays only a subset of the information displayed in the table format. The information displayed differs between formats. PowerShell determines how to format the results based on object type. In other words, the format type, layout, and properties returned are specific to the type of object. For example, the results returned by the Get-ChildItem cmdlet when retrieving file system information will be different from the results returned when retrieving information about the registry because they’re two different types of objects, even though the same cmdlet is used. PowerShell uses a set of complex XML format (.ps1xml) files to determine how to display the results.

Controlling Statement Output
When you execute a statement, PowerShell applies the default format to the output and sends that output to the console window, unless you override this behavior by using one the four format cmdlets I just described. However, you can also control where to send that output. PowerShell provides six cmdlets for controlling output:

  • The Out-Host cmdlet sends output to the PowerShell console. This is the default output cmdlet, so you don’t need to specify it.
  • The Out-Default cmdlet sends output to the default formatting cmdlet. In addition, Out-Default delegates the outputting process to the Out-Host cmdlet. You don’t need to specify the Out-Default cmdlet.
  • The Out-File cmdlet sends output to a specified file.
  • The Out-Null cmdlet deletes output and doesn’t send it to the PowerShell console.
  • The Out-Printer cmdlet sends output to a printer.
  • The Out-String cmdlet converts the pipeline object to an array of strings. You can find additional information about each cmdlet in the PowerShell Help files.

To control a statement’s output, add the output cmdlet at the end of your pipeline. For example, the following statement formats the PowerShell process information into a list, then sends that list to the C:\SysInfo\ps.txt file:

Get-Process powershell |
Format-List | 
Out-File C:\SysInfo\ps.txt

When you send output to a file, PowerShell saves the content to the file but doesn’t display it in the console. You can use the Out-File cmdlet to send output to any type of file that makes sense. For example, you wouldn’t want to send text to a .bmp file. Although this wouldn’t throw an error, you wouldn’t be able to view anything when you opened the file.

The Out- File cmdlet lets you choose whether to append the output to the file or replace the existing content with the output. By default, it replaces any existing content. To append the output, you need to add the -append switch to the Out-File cmdlet:

Get-Process powershell | 
Format-List | 
Out-File C:\SysInfo\ps.txt `
-append

Sorting Statement Output
In addition to formatting output, you’ll often find that you’ll want to sort output. To sort output, you use the Sort-Object cmdlet. This cmdlet takes the input objects from the pipeline and sorts them based on the criteria you define. As I mentioned previously, Power- Shell streams the results down the pipeline from one command to the next. However, when you sort data, the Sort-Object cmdlet waits until it has all the results (objects) and then sorts them. This effectively stops the streaming process until everything is sorted. For a small result set, this isn’t a problem, but it could impact performance when retrieving large amounts of data.

Still, the Sort-Object cmdlet can be a handy tool. For example, suppose you want to retrieve a list of the items in the C:\Windows folder. You can use the Get- ChildItem cmdlet in a statement such as

 dir c:\windows | 
where {$_.length -gt 500000} |
sort -property length 
-descending

This statement passes the output object from the Get-ChildItem cmdlet (referenced by the dir alias) to the Where-Object cmdlet (referenced by the where alias). The Where-Object cmdlet specifies that the length must be greater than (specified by -gt) 500,000 bytes. The results are then passed down the pipeline. When the Sort- Object cmdlet (referenced by the sort alias) has all the objects, it sorts them based on the defined criteria.

In this case, the Sort-Object cmdlet first specifies that the sorting should be based on the Length property. The -descending switch indicates that the results should be sorted in descending order, as shown in Figure 6, page 61. If you don’t specify the -descending switch, the results are sorted in ascending order. In addition, you can specify more than one property (separated by commas) on which to base the sort order. PowerShell sorts the data first by the first property specified, then by the second, and so on.

Moving Forward
As this lesson demonstrates, the PowerShell pipeline is a powerful feature that lets you combine multiple cmdlets to perform a series of successive operations on one or more objects. You can pipe together multiple cmdlets into a statement, format the output from that statement, specify where to place the output, and even sort the outputted information. In the lessons to follow, you’ll learn how to enhance your statements even further so you can take full advantage of PowerShell’s pipeline capabilities.

End of Article

   Previous  1  [2]  Next  


Reader Comments
Fabulous information. I am already using the examples to produce useful work.
The teaching style is very user friendly, Thank you very much

ehelmamericanbibleorg March 06, 2008 (Article Rating: )


The article information is very easy to follow. Thank you very much.

Marie February 01, 2009 (Article Rating: )


You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Top Viewed ArticlesView all articles
WinInfo Short Takes: Week of November 9, 2009

An often irreverent look at some of the week's other news, including some more Windows 7 sales momentum, some Sophos stupidity, Microsoft's cloud computing self-loathing, more whining from the browser makers, Zoho's "Fake Office," and much, much more ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

Windows 7 Sets Sales Record

Microsoft CEO Steve Ballmer described Windows 7's first ten days of sales as "fantastic" while in Japan yesterday. ...


Related Articles PowerShell 101, Lesson 1

Essential Windows PowerShell Commands

PowerShell Scripting

Dig Out by Digging Into PowerShell

Scripting Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events WinConnections and Microsoft® Exchange Connections

Deep Dive into Windows Server 2008 R2 presented by John Savill

PowerShell 201 - eLearning Series with Paul Robichaux

Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement