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

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.