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  


Windows IT Pro Community
Blogs





Top Viewed ArticlesView all articles
No Jobs, No Excitement at Apple's Last Macworld Keynote

Apple CEO Steve Jobs made the right move in skipping out on his company's last appearance at Macworld: In a Tuesday keynote address at the conference, Apple had no interesting new products to sell, opting instead to spend mind-numbing amounts of time on ...

Where is Microsoft NetMeeting in Windows XP?

...

Command Prompt Tricks

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


Related Articles PowerShell 101, Lesson 1

Essential Windows PowerShell Commands

PowerShell Scripting

Dig Out by Digging Into PowerShell

Windows OSs Whitepapers Why SaaS is the Right Solution for Log Management

Related Events Virtualization Forum: Optimizing Storage, Networks, Desktops, and Security

PowerShell 201 - eLearning Series with Paul Robichaux

Cloud Computing Forum: Integrating Software, Server and Storage as a Service into Your Enterprise IT Delivery Model

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 Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


SQL Server Magazine Office & SharePoint Pro Windows Dev Pro ITTV
IT Library Technology Resource Directory Connected Home Windows Excavator Windows SuperSite
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2009 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing