Prof. Powershell

WHILE You Were Away...

Lesson in Logic #2: The WHILE statement keeps things rolling in your PowerShell scripts.

Last time, we looked at the IF command. Here's another logic construct you are likely to use: the WHILE statement. The underlying concept is similar to IF. Some condition will be evaluated and if it is True, then a block of code is executed:

while (<condition>){<command_block>}

The condition must be something that will return a True or False value. As long as the condition is True, any command in the code block will execute. When the code block reaches the end, the condition is checked again. If it is still true, then the code block is repeated:

PS C:\> $x=1
PS C:\> while ($x -lt 10) {$x
>> $x++
>> }
>>
1
2
3
4
5
6
7
8
9
PS C:\>

In this demonstration I'm setting $x to 1. As long as $x is less than 10, I'll display the value of $x and increment the value by 1.

The last part is critical. If the condition you are watching will never become false, the code block will repeat indefinitely. Most of the times this is something you'll want to avoid.

Here's another way you might use While in a script:

while ((get-service spooler).status -eq "Running") {sleep -millisecond 500}
write-host "The spooler service has stopped!" -foregroundcolor Red

As long as the spooler service is running, the PowerShell code in the curly braces will execute. In this situation the script sleeps for half a second and checks again. If the spooler service is stopped, then the condition will be false and the next line in the script will execute, which displays a message.

A final point I want to stress is that there's no guarantee the code block will ever run. In my first example, suppose $x is 11. When the While statement evaluates the expression, it will be False so the code block won't run. Depending on the situation this may or may not be desirable. Next time I'll show you an alternative.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular