Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  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
Anti-Virus Vendors Prepare for War with Microsoft ... Again

When Microsoft announced its Windows Live OneCare security and PC health product over five years (as MSN OneCare), Symantec, McAfee, and the other consumer-oriented security vendors reacted with stunning vigor. ...

What You Need to Know About Microsoft's x64 Server Product Plans

What do Longhorn Server, Windows Compute Cluster Server, and Windows Vista have in common? The x64 platform. ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...


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 WinConnections and Microsoft® Exchange Connections

PowerShell 201 - eLearning Series with Paul Robichaux

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 Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format

Test Drive IT Solutions and Get Free Music Downloads
Solve your toughest IT problems with these free downloads and receive 5 free music downloads!


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 DevProConnections IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home asp.netPRO Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement | Reprints and Licensing