O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.3. Loops: Repeatedly Executing Blocks of Code

Loops are the last piece of the control flow puzzle. They allow us to repeatedly execute a block of code, usually while a condition is satisfied. We can use them to repeat an action many times, to walk over a collection of objects and perform an action on each and every one of them, wait indefinitely for an external condition to become true, and much more.

2.3.1. The Simplest Loop: while

What could be simpler than the ability to repeat something while a condition is true? The while loop allows us to do exactly that. Its general form is

while (<condition>)
{
    <action block>
}

Here is how to use it to wait for the notepad process to exit:

PS> while (Get-Process notepad -ErrorAction SilentlyContinue){ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required