foreach
can be used to iterate over an array: $ar = 10 .. 14 foreach ($elem in $ar) { $elem / 3 } # 3.33333333333333 # 3.66666666666667 # 4 # 4.33333333333333 # 4.66666666666667
continue
statement allows to skip specific iterations: forEach ($val in 'foo', 'bar', 'baz') { if ($val -eq 'foo') { write-host 'Skip processing of foo' continue } write-host "Processing $($val)" }
break
statement causes the foreach
loop to be immediately terminated. foreach ($num in 1 .. 10) { if ($num -eq 5) { break } write-host "$($num) * $($num) = $($num * $num)" }
get-childItem
retuns an array of objects, it can be easily combined with foreach
to iterate over some files in a directory: foreach ($fileObj in get-childItem '*i*.ps1') { # # Convert the System.IO.FileInfo object to a string: # $fileStr = split-path -leaf $fileObj write-output $fileStr }
foreach
can be used on any cmdLet that returns an array of objects. System.Collections.IEnumerator
interface in order for foreach
to be able to iterate over the object. This example tries to demonstrate how an object can implement this interface. break
statement exits a loop. for
statement.