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 


April 2008

PowerShell 101, Lesson 3

How to use PowerShell's operators and wildcards
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 Find Out a Cmdlet's Properties

Executive Summary:

Windows PowerShell offers many different types of operators. For example, its comparison and logical operators let you create conditions that PowerShell evaluates to determine whether it should take specific actions. And its arithmetic operators let you not only perform mathematical calculations but also concatenate strings.


In PowerShell, you can connect cmdlets together to create a pipeline and use the Where-Object cmdlet to filter objects passed down that pipeline. For example, in the following statement, objects from the Get-ChildItem (referenced by the dir alias) cmdlet are piped to a Where-Object cmdlet (referenced by the where alias), which filters out all items in C:\Windows, except those larger than 500,000 bytes:

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

Notice that the Where-Object cmdlet includes an expression that’s enclosed in braces ({ }). The expression states that the current value of the Length property must be greater than 500,000. The value of the Length property is retrieved by using $_.length. The $_ symbol references the current object in the pipeline, and .length retrieves the value of the Length property. The expression then uses the -gt (greater than) operator to compare the Length property value to the value of 500,000.

As with any language, PowerShell provides a set of operators that let you create expressions you can incorporate into your statements. An expression is a block of code that PowerShell evaluates; the result of that evaluation determines what action to take. For example, in the preceding statement, PowerShell determines whether the Where-Object expression is true or false. When the expression evaluates to true—that is, the current object’s Length property value is greater than 500,000—that object is passed down the pipeline and displayed in the output. If the expression evaluates to false—that is, the current object’s Length property value isn’t greater than 500,000—the object is discarded and not displayed in the output.

PowerShell includes a variety of operators that you can use in your expressions. This lesson describes many of those operators and provides examples of how to use them. In addition, the Web-exclusive sidebar “How to Find Out a Cmdlet’s Properties,” www.windowsitpro.com, InstantDoc ID 98175, discusses how to find property names, such as those used in the Where-Object expressions in the examples provided.

Comparison Operators
As the name suggests, comparison operators compare values. When an expression contains a comparison operator, PowerShell compares the value to the left of the operator with the value to the right of it. You saw this idea in the preceding example, in which the Length property value is compared to 500,000. PowerShell provides many comparison operators, as Table 1, shows. Let’s examine some of those operators to see how they work.

The following statement does the opposite of the preceding example— it returns items whose lengths are smaller than 500,000 bytes:

 dir c:\windows |
  where {$_.length -lt 500000}

As you can see, the only difference between the two statements is the comparison operator. This statement uses the -lt (less than) operator rather than the -gt operator.

Other comparison operators follow the same logic. The following statement uses the -eq (equal to) operator to compare the Responding property value to the string true in order to retrieve a list of responding processes:

 get-process |
  where {$_.responding -eq “true”}

For the Where-Object expression to evaluate to true, the Responding property value must equal true. As a result, only responding processes are returned, as Figure 1 shows.

By default, all comparison operators perform case-insensitive comparisons. If you want to be more precise in your code, you can add the letter i to a comparison operator (e.g., -ieq) to explicitly specify a case-insensitive comparison. However, because this is the default behavior, adding the i isn’t necessary.

You can make any comparison casesensitive by adding the letter c to the comparison operator (e.g., -ceq). For example, the statement

 “True” -eq “true”

evaluates to true because it ignores case, whereas the statement

 “True” -ceq “true”

evaluates to false because it takes case into account.

I realize that these are very basic examples, but when working in a Windows environment, case often isn’t a concern because filenames, process names, and other item names are case-insensitive. But as you become more familiar with PowerShell and learn how to retrieve other types of lists in which case-sensitivity is important, you’ll find being able to make an operator casesensitive useful.

Another useful PowerShell feature is wildcards. For example, if you don’t know the exact name of an item when creating an expression to compare values, you can use wildcards in the compared value (the value after the operator). Table 2 describes the wildcards that PowerShell supports.

Continued on page 2

   Previous  [1]  2  3  Next 


Reader Comments
I'm not sure what to make of this...

Figure 5 is supposed to return all non-Microsoft processes.

I know that the CSRSS process was purchased from Citrix a few years ago and probably not recoded by Microsoft, but why in the world would the System and WINLOGON processes be listed as non-Microsoft?

maddmike April 17, 2008 (Article Rating: )


Very good articles

crjo April 22, 2008 (Article Rating: )


You must log on before posting a comment.

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




Learning Path To read the previous "PowerShell 101" lessons, go to
"PowerShell 101, Lesson 1"

"PowerShell 101, Lesson 2"


For more information about how to use the Get-Member cmdlet
"What Can I Do With Windows PowerShell? Using the Get-Member Cmdlet"

"Get-Member"


For more information about using PowerShell operators
"Windows PowerShell Constructs"

"What Can I Do With Windows PowerShell? Using the Where-Object Cmdlet"


If you're beyond the basics, check out
"PowerShell Queries for Failed Services on Remote Machines"

"PowerShell One-Liners for Accessing WMI"


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

Remote Control Software

Control remote machines from home or the office. ...

WinInfo Short Takes: Week of July 21, 2008

An often irreverent look at some of the week's other news, including an iPhone 3G defeat, 180 million copies of Windows Vista in the wild, Microsoft earnings some more Yahoo silliness, Wii vs. Xbox 360, EU vs. Intel, AMD ousts its CEO, and so much more ...


Related Articles PowerShell Script Lets You Check Patches' Status

How to Get Information About Installed Applications Without Using WMI

PowerShell Pointers

Quest Freeware Product Puts a Familiar, GUI Face on 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

Shortcut Guide to SQL Server Infrastructure Optimization
With right tools and techniques, you can have a top-performing SQL Server infrastructure without having to cram your data centers so that they're overflowing. Download this eBook to learn how.

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

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

Continuous Data Protection and Recovery for Exchange
Read this white paper to learn about Continuous Data Protection (CDP), Exchange 2007's local continuous replication and cluster continuous replication features.

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!

Tips to Managing Messaging
Discover three fundamental mail and messaging management services - security, availability and control services - and how you can implement them in a Microsoft-centric mail and messaging environment.

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!



Drag & Drop Data Mapping Tool
Try this award-winning data mapping, & transformation tool that supports multiple databases, flat files, Web services, EDI, Excel 2007, & more! Free trial for 30 days!

Overcome bloated Windows file systems
Crossroads FMA delivers powerful yet inexpensive data migration

Bandwidth Monitoring Tool from SolarWinds
Identify largest bandwidth users in seconds. Get the free download now.

Speed Deployment of Vista and Microsoft Office
Read this white paper to learn how you can maximize your Vista and Office investments while lowering costs and increasing efficiency.

Integrated Virtualization Done Right
Download this white paper on server virtualization to begin improving resource utilization and lowering operating costs.

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.

KVM over IP Solutions
Learn about a KVM over IP solution that is specifically designed to meet the needs of the distributed IT environment.
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
IT Library Technical Resources Directory Connected Home Windows Excavator 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