A loop is a sequence of instruction(s) that is continually repeated until a certain condition is reached. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming. A loop lets you write a very simple statement to produce a significantly greater result simply by repetition. If the condition has been reached, the next instruction "falls through" to the next sequential instruction or branches outside the loop.
for ( <Initialization>; <Condition>; <Repetition> ) { <Script_Block> }
<Collection> | Foreach-Object { <Script_Block_with_$__as_current_item> }
foreach ( <Item> in <Collection> ) { <Script_Block> }
while ( <Condition> ){ <Script_Block> }
do { <Script_Block> } while ( <Condition> )
do { <Script_Block> } until ( <Condition> )
<Collection>.foreach( { <Script_Block_with_$__as_current_item> } )
There are multiple ways to run a foreach-loop in PowerShell and they all bring their own advantages and disadvantages:
Solution | Advantages | Disadvantages |
---|---|---|
Foreach statement | Fastest. Works best with static collections (stored in a variable). | No pipeline input or output |
ForEach() Method | Same scriptblock syntax as Foreach-Object , but faster. Works best with static collections (stored in a variable). Supports pipeline output. | No support for pipeline input. Requires PowerShell 4.0 or greater |
Foreach-Object (cmdlet) | Supports pipeline input and output. Supports begin and end-scriptblocks for initialization and closing of connections etc. Most flexible solution. | Slowest |
$foreach = Measure-Command { foreach ($i in (1..1000000)) { $i * $i } }
$foreachmethod = Measure-Command { (1..1000000).ForEach{ $_ * $_ } }
$foreachobject = Measure-Command { (1..1000000) | ForEach-Object { $_ * $_ } }
"Foreach: $($foreach.TotalSeconds)"
"Foreach method: $($foreachmethod.TotalSeconds)"
"ForEach-Object: $($foreachobject.TotalSeconds)"
Example output:
Foreach: 1.9039875
Foreach method: 4.7559563
ForEach-Object: 10.7543821
While Foreach-Object
is the slowest, it's pipeline-support might be useful as it lets you process items as they arrive (while reading a file, receiving data etc.). This can be very useful when working with big data and low memory as you don't need to load all the data to memory before processing.