Looping for each

Looping for each

PowerShell's Foreach statement is also known as the Foreach loop. Arrays, strings, numbers, etc., can be looped over using the Foreach keyword. This loop is mainly used when working with a single object at a time.

Syntax

The following block shows the syntax of Foreach loop:

"Foreach($in $)  

   {  

         Statement-1  

         Statement-2  

         Statement-N  

    } "

A single value of a variable or an object in Stated-N changes over each iteration. It is an array or a collection of numbers and strings. PowerShell automatically creates the variable $ when this loop executes. A syntax block contains single or multiple statements that are executed for each item in a collection.

Flowchart of ForEach loop


Examples

Example1: This example displays the value of an array using a foreach loop:

"PS C:\> $Array = 1,2,3,4,5,6,7,8,9,10  

PS C:\> foreach ($number in $Array)  

>> {  

>> echo $number  

>> }  "

Output:

1

2

3

4

5

6

7

8

9

10

The array $Array is created and initialized with the integer values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Whenever the Foreach statement executes, it assigns the integer value '1' of an array to the $number variable. Next, it uses the echo cmdlet to display the number 1. The next time through the loop, $number is set to 2, and so forth. Upon displaying 10 in the Foreach loop, PowerShell terminates the loop.

Example2: The following example shows the files of a folder using foreach loop:

"PS C:\> foreach($file in get-childitem)  

>> {  

>>  echo $file  

>> }  "

Output:

"     Directory: C:\

Mode                LastWriteTime         Length Name

----                -------------         ------ ----

d-----       23-02-2019     13:14                found.000

d-----       28-12-2017     19:44                Intel

d-----       04-07-2018     10:53                Office 2013 Pro Plus

d-----       15-09-2018     13:03                PerfLogs

d-----       09-10-2019     11:20                powershell

d-r---       22-08-2019     15:22                Program Files

d-r---       03-10-2019     10:23                Program Files (x86)"

For example, the get-childitem cmdlet returns a list of items (files) in the foreach statement.

Example3: The following example displays the value of an array using foreach loop:

"PS C:\> $fruits= "apple", "orange", "guava", "pomegranate", "Mango"  

PS C:\> foreach ($item in $fruits)  

>> {  

>> echo $item  

>> }"

Output:

apple

orange 

guava

pomegranate

Mango