Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  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: )


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
Friday at PASS Europe 2006

Kevin talks about the closing day of the event and shares a funny Microsoft film. ...

More fun TechEd 2005 Resources

Kevin points out some more TechEd resources ...

Microsoft Announces Upcoming Xbox 360 Milestones

Microsoft announced this morning that it will deliver a completely new user interface for the Xbox 360 on November 19, the New Xbox Experience, an update that will result in a "completely new Xbox 360." The company also revealed that it will be extending ...


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

Are You Satisfied?

A Preliminary Look at Deployment Plans for Microsoft Windows Vista

Related Events 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.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Microsoft Exchange & Windows Connections event returns to Las Vegas Nov 10 - 13
Connections returns to Las Vegas for this exciting event where each attendee will receive SQL Server 2008 standard with 1 CAL. Co-located with Microsoft ASP.NET, SQL Server, and SharePoint Connections with over 250 in-depth sessions.

Free Online Event! Virtualization:Get the Facts!
Register now and attend this free, live in-depth online conference on November 13 and 20, 2008, produced by Windows IT Pro. All registrants are eligible to receive a complimentary one-year digital subscription to Windows IT Pro (a $49.95 value)!

Check Out Hyper-V Video on ITTV
Watch Karen Forster's interview on Hyper-V's performance on ITTV.net.

Ease Your Scripting Pains with the Flexibility of PowerShell!
Join MVP Paul Robichaux on December 11, 2008 at 11:00 AM EDT as he equips you with PowerShell basics in 3 introductory lessons, each followed by a live Q&A session—all on your own computer!

Latest Advancements in SSL Technology
There are a variety of different kinds of SSL to explore to ensure customer data is kept confidential and secure. In this paper, we will discuss some of these SSL advances to help you decide which would be best for your organization.

PASS Community Summit 2008 in Seattle on Nov 18-21
The don’t-miss event for Microsoft SQL Server Professionals. Register now and you’ll enjoy top-notch Microsoft and Community speakers and more.



Solving PST Management Problems
In this white paper, read about the top PST issues and how to administer local/network PST Files.

Get Protected -- Data Protection Manager 2007
Protect your virtualized environment with Data Protection Manager

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Maximize Your SharePoint Investment: Get Your Data Moving
Watch this web seminar now to learn how to maximize your SharePoint investment! Join us as we take a look at the complex business of securing, accessing and managing vast amounts of information in a global network and various ways to get your data moving.
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 Windows Dev Pro IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing