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

The Desktop tab is missing from the Display Properties in Windows XP?

...

Microsoft's Olympic Gold

With world records being broken at a dizzying pace, the 2008 Summer Olympics in Beijing has drawn massive audiences from around the world, most watching the games via traditional TV coverage. But behind the scenes, a massive array of technology is ...


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.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

WinConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

Deploying SharePoint! In-Person Event Series – 8 Cities
Discover best practices and tips for deploying the perfect SharePoint infrastructure. Early Bird Price of $99 extended till Sept. 15th.

Find a new job now on the all new IT Job Hound!
Search jobs, post your resume, and set up job e-mail alerts!

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Top Tools for Virtualization Disaster Recovery & Replication
View this web seminar on August 14th to learn about two tools that will result in faster backup and restore with P2V disaster recovery.

SharePointConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

VMworld 2008 - Sign Up Today!
Join your peers on September 15-18 at The Venetian Hotel in Las Vegas as VMware hosts VMworld 2008, the leading Virtualization event.



When managing just VMware isn’t enough
Plan/Manage/Secure – NetIQ VMware management. Download whitepaper.

What’s up with your network? Find out with ipMonitor
Availability monitoring for servers, applications and networks – FREE trial

Microsoft® Tech•Ed EMEA 2008 IT Professionals
Advance your thinking with new ideas and practical real-world solutions at Microsoft’s FIVE day technical infrastructure conference 3-7 Nov., 2008. Register before 26 September 2008 to save €300.

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.

Are You Really Compliant with Software Regulations?
View this web seminar that will help you with compliance best practices and check out a management solution to assure that you won’t be in jeopardy of an audit.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16 in London.
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 Technical Resources 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