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

Executive Summary:

Windows PowerShell provides far more power and flexibility than traditional Windows command shells, such as cmd.exe. To help you take advantage of that power, this six-article series explains how to use PowerShell to perform various tasks. In this lesson, you’ll learn how to link cmdlets into a pipeline to create PowerShell statements. You’ll also learn how to format and sort output from those statements.


In “PowerShell 101, Lesson 1” (February 2008, InstantDoc ID 97742), I introduced you to the concept of cmdlets and how to run basic PowerShell commands. I also showed you how to use aliases and how to use PowerShell’s Get- cmdlets to get help when creating commands. For example, you can use the Get-ChildItem cmdlet to retrieve a list of items in a folder or the Get-Content cmdlet to retrieve the content of a text file. With cmdlets and their parameters, you can run a wide variety commands that display system information or carry out tasks.

However, a cmdlet alone might not always provide the full functionality you require. For this reason, PowerShell lets you create pipelines that link cmdlets together to carry out complex operations and refine the system information you retrieve. In this lesson, you’ll learn how to link cmdlets into a pipeline to create PowerShell statements. You’ll also learn how to format and sort statement output.

Implementing a Pipeline
A PowerShell pipeline is a series of cmdlets that pass objects from one cmdlet to the next. Each cmdlet generates an object and passes it down the pipeline, where it is received by the next cmdlet. The receiving cmdlet uses that object as input and generates its own output as an object. You connect cmdlets into a pipeline by using the pipe (|) operator.

Pipelining in PowerShell is different from pipelining in other command shell environments, such as the Windows command shell. In traditional environments, a command’s results are returned as a single result set, which means that the entire result set must be generated before any information is passed down the pipeline. The first result is returned at the same time as the last result. In PowerShell, however, the results are streamed through the pipeline. As soon as a command returns a result, it passes it down the pipeline, and that result is immediately available to the next command in the pipeline.

Let’s look at an example that will help you understand how a pipeline works. If you run the cmdlet

Get-Service

you’ll receive a list of the services installed your system, similar to the list in Figure 1. Notice that the cmdlet returns the status, name, and display name of each service. Suppose you want to retrieve a list of running services only. You can pipe the output from the Get- Service cmdlet to the Where-Object cmdlet, which filters the output based on the specified criteria, as shown in the statement

Get-Service |
 Where-Object {$_.status -eq ‘running’}

As you can see, you use a pipe operator to connect the two cmdlets. The Get-Service cmdlet generates an object that contains the servicerelated information. The object is passed down the pipeline to the Where-Object cmdlet. The Where-Object cmdlet receives the object and uses the information as input. The Where-Object cmdlet filters the information based on the Status property value. Notice that the Where-Object cmdlet includes an expression enclosed in braces ({ }). If the expression evaluates to true, the Where-Object passes that object down the pipeline and filters out any other object.

In this case, the Where-Object expression states that the Status property value must be equal to (specified by the -eq operator) the string running. Status is one of the properties available to the object generated by the Get- Service cmdlet. When an object is passed down the pipeline, you can access its properties, as I’ve done in the Where-Object expression. To access a property in the pipeline in this manner, you use the $_ built-in variable. This variable holds the current object within the pipeline each time the Where-Object cmdlet loops through the pipeline results. You can then reference the object’s properties, as in $_.Status. The output now looks similar to that in Figure 2. (You’ll learn more about the Where-Object cmdlet, object properties, and operators in later lessons.)

Note that you’d typically enter the statement just given on one line in the Power- Shell console window. However, column widths in the magazine force us to print this statement on more than one line. Also note in Figure 2 the >> character sequence at the beginning of some of the lines in the command. This character sequence constitutes a multiline prompt. For information about when you’d want to enter a statement on multiple lines in the PowerShell console window and how to properly do so.

Now suppose you want to list only the display name of each running service. You can pipe the output of the Where-Object cmdlet to the Select-Object cmdlet:

Get-Service |
where {$_.status -eq ‘running’} |    
select displayname

In this statement, the Select-Object cmdlet receives the object from the Where-Object cmdlet. In this case, the statement uses the where alias to reference the Where-Object cmdlet and the select alias to reference the Select-Object cmdlet. In the select cmdlet, you specify the name of the property (or properties) that you want to display. For this example, I’ve specified the displayname property. The statement will now output results similar to those in Figure 3.

The key to using pipelines is to remember that you’re always working with objects. Each cmdlet generates an object that the next cmdlet in the pipeline receives. Even the final cmdlet generates an object that outputs the statement results. As you progress through the lessons, you’ll learn how to use those objects and their properties to refine your PowerShell statements.

Formatting Statement Output
By default, PowerShell formats a statement’s output based on the type of data in that output. For example, the following statement returns data about the PowerShell process:

Get-Process powershell

Continue to page 2

   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
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Managing Virtual Sprawl

As some wise person once said, nothing is ever truly free. Such is the case with VMs, which can quickly mutate from a cost-reducing Dr. Jekyll into a time-consuming, profligate nightmare that would do Mr. Hyde proud. ...

How can I uninstall the Microsoft Java Virtual Machine (JVM) from Windows XP?

...


Related Articles PowerShell 101, Lesson 1

Essential Windows PowerShell Commands

PowerShell Scripting

Dig Out by Digging Into PowerShell

Windows OSs Whitepapers Replay for Exchange: Enterprise Protection and an Affordable Price

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.


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Critical Challenges of ESI & Email Retention
Are you storing too much electronic information? Get expert legal advice and better understanding of what you are required to do as an IT professional.

Become a fan of Windows IT Pro on Facebook!
Join us on Facebook and be a fan of Windows IT Pro!

Sustainable Compliance: Are You Having a Resource Crisis?
Read this white paper to examine trends in compliance and security management and review approaches to reducing the cost and operational burden of compliance.

Rev Up Your IT Know-How with Our Recharged Magazine!
The improved Windows IT Pro provides trusted IT content with an enhanced new look and functionality! Get comprehensive coverage of industry topics, expert advice, and real-world solutions—PLUS access to over 10,000 articles online. Order today!

Get It All with Windows IT Pro VIP
Stock your IT toolbox with every solution ever printed in Windows IT Pro and SQL Server Magazine plus bonus Web-exclusive content on hot topics. Subscribe to receive the VIP CD and a subscription to your choice of Windows IT Pro or SQL Server Magazine!



Order Your Fundamentals CD Today!
Gain an introduction to Exchange, learn server security requirements, and understand how unified communications can play a role in your messaging strategies with this free Exchange CD.
Windows IT Pro Home Register About Us Affiliates / Licensing Media Kit Contact Us/Customer Service  
SQL Connected Home IT Library SuperSite FAQ Wininfo News
Europe Edition Office & SharePoint Pro Windows Dev Pro Windows Excavator 
 
 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