Thursday, 5 December 2019

ForEach (loop statement)

https://ss64.com/ps/foreach.html


Loop through a set of input objects and perform an operation (execute a block of statements) against each.
Syntax
      ForEach [-Parallel] (item In collection) {ScriptBlock}

key
   item         A variable to hold the current item
   collection   A collection of objects e.g. filenames, registry keys, servernames
   ScriptBlock  A block of script to run against each object.
   -Parallel    Run the commands once for each item in parallel (PowerShell Workflow only).
The collection will be evaluated and stored as an array in memory before the scriptblock is executed.
The foreach statement does not use pipelining (unlike ForEach-Object ) If you use foreach in a command pipeline PowerShell will actually run the foreach alias that calls ForEach-Object.
Use the ForEach statement when the collection of objects is small enough that it can be loaded into memory.
Use the ForEach-Object cmdlet when you want to pass only one object at a time through the pipeline, minimising memory usage. In most cases ForEach will run faster than ForEach-Object, there are exceptions, such as starting multiple background jobs. If in doubt test both options with Measure-Command.
ForEach -Parallel is valid only in a PowerShell Workflow, there is currently no general parallel support for the foreach keyword.
In PowerShell 4.0 and later, the ForEach method provides even faster performance.
Examples
Loop through an array of strings:
 $trees = @("Alder","Ash","Birch","Cedar","Chestnut","Elm")

 foreach ($tree in $trees) {
   "$tree = " + $tree.length
 }
Loop through a collection of the numbers, echo each number unless the number is 2:
 foreach ($num in 1,2,3,4,5) {
  if ($num -eq 2) { continue } ; $num
 }


Loop through a collection of .txt files:
  foreach ($file in get-ChildItem *.txt) {
    Echo $file.name
  }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive