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 


November 2008

Controlling Your Code's Flow with PowerShell's Conditional Statements

Lesson 2 in the PowerShell 201 series explores how to use the if, for, and while statements
RSS
Subscribe to Windows IT Pro | See More Systems Administration Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

Executive Summary: Lesson 2 in Robert Sheldon's PowerShell 201 series covers the if, for, and while statements. This lesson explains the various components that make up these statementsand provides examples of how to use each type of statement for tasks such as retrieving a list of text files in a folder and retrieving a list of processes and the number of handles used by those processes.

Windows PowerShell provides several ways to control the flow of code, including the if, for, and while statements. You can use these three statements to define conditions and the actions to occur when those conditions are met. You can even specify the actions to occur when a condition isn’t met. Let’s look at the various components that make up the if, for, and while statements and how to use each type of statement for tasks such as retrieving a list of text files in a folder and retrieving a list of processes and the number of handles they’re using.

The if Statement
An if statement contains a conditional code block, which is enclosed in parentheses, and a script block, which is enclosed in braces. The conditional code block specifies a condition, whereas the script block specifies one or more actions. When the condition is met—that is, when the conditional code block evaluates to true—PowerShell runs the script block. When the conditional code block evaluates to false, PowerShell skips the script block.

For example, the following code initializes the $files variable, then defines a basic if statement:

$files = dir c:\archivedfiles\*.txt
if ($files -ne $null)
{
  "There are files in this folder."
  write-host
}

The first line assigns a collection of text files to $files. The if statement uses the $files variable in its conditional code block ($files -ne $null) to specify that the variable must not be null. In other words, the variable must contain text files. When there are text files, the conditional code block evaluates to true and the script block runs and displays the message There are files in this folder. When the conditional code block evaluates to false, the if statement ends. As a result, no message is displayed when the folder doesn’t contain text files.

At times, you might want to take a specific action when a conditional code block evaluates to false. You can do so by adding an else clause. This clause begins with the keyword else, followed by its own script block. The else script block runs when none of the if statement’s conditional code blocks evaluate to true. Take, for example, the following if statement:

$files = dir c:\archivedfiles\*.doc
if ($files -ne $null)
{
  "There are Word " +
  "files in this folder."
  write-host
}
else
{
  "No Word files in this folder."
  write-host
}

When the conditional code block ($files -ne $null) evaluates to false, the else script block runs and displays the message No Word files in this folder.

In this example, the if statement takes into account two scenarios: the folder contains Microsoft Word files or doesn’t contain them. However, there might be times when you want the statement to handle more than two scenarios. In these situations, you can add a few elseif clauses. (If you need to use many elseif clauses, you should consider using a switch statement, which I’ll discuss in the next lesson.) For each elseif clause, you define a conditional code block and a script block. When the conditional code block evaluates to true, the script block runs.

For example, the code in Listing 1 uses elseif clauses to determine how many files are in a folder. In this code, one if statement is embedded in another if statement. The code begins by assigning a collection of text files to $files. The outer if statement then checks to see whether $files is null. I perform this check rather than using the Count property to determine the number of files because I had to provide for the possibility that there might be only one file in the folder. The Count property is available only when there’s two or more files in a folder. When there’s more than one file, PowerShell treats $files as an array, which supports the Count property. When there’s only one file, PowerShell treats $files as a scalar (i.e., single) value, which means the Count property isn’t available.

When the outer if statement finds that $files is null, the else clause in callout B runs. This clause’s script block displays the message No files in folder. When $files isn’t null, the inner if statement in callout A runs. The inner if statement’s conditional code block defines three conditions: an if condition and two elseif conditions.

The if condition ($files.count -gt 10) specifies that the number of text files must be greater than 10. When this conditional code block evaluates to true, the script block displays the message More than 10 files in folder.

The first elseif condition ($files.count -gt 7 -and $files.count -le 10) specifies that the number of text files must be greater than 7 but less than or equal to 10. When this conditional code block evaluates to true, the script block displays the message 8-10 files in folder.

The second elseif condition ($files.count -gt 4 -and $files.count -le 7) specifies that the number of text files must be greater than 4 but less than or equal to 7. When that conditional code block evaluates to true, the script block displays the message 5-7 files in folder.

If none of the three conditional code blocks evaluate to true, the else clause’s script block runs. It displays the message Fewer than 5 files in folder.

Continue to page 2

   Previous  [1]  2  Next 


Learning Path To read the previous lesson in the PowerShell 201 series, go to
"Iterating Through Collections with PowerShell's foreach Loops"


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

Home Tech? Work Tech? Increasingly, It's Just Tech

Paul discusses how the consumer market is influencing business technology in ways that are unprecedented. ...

Where is Microsoft NetMeeting in Windows XP?

...


Related Articles Managing AD User Accounts with PowerShell

PowerShell 101, Lesson 5

PowerShell 101, Lesson 3

Essential Windows PowerShell Commands

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.


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 © 2009 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing