In fact, many constructs in Windows PowerShell should be familiar to
anyone who has worked with the C programming language.
The Foreach statement is used to loop through a collection of items. Unlike the For
loop where you define a variable, a stop condition, and repeating code, the Foreach
449 Chapter 13: Windows PowerShell
statement is designed to take a collection as its parameter and run a block of code for
each item in that collection (hence the name). Foreach statements have the following
syntax:
Foreach ($
- in $) {
}
This is an extremely useful looping statement. The following code snippet shows
how you can use Foreach to display the name of an item in the Windows directory:
Foreach ($file in Get-ChildItem C:\Windows) {
write-host $file
}
Hopefully a light bulb just lit up above your head. You can run any PowerShell code
in the command block so you can easily convert this Foreach example to do something
useful. For example, you might use this code to rename every item in a specific folder.
You can use Foreach to iterate through any collection, including arrays.
The While statement, otherwise known as a While loop, is similar to a For loop in
that it runs a command block any number of times while a condition is true, except its
only parameter is a condition statement. This means that initializing or incrementing any
variables to make sure the condition will eventually evaluate to false so that the loop will
end has to be done separately.
Pages:
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479