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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.