spot_img

ForEach loop

The Foreach loop is also known as a Foreach statement in PowerShell. The Foreach is a keyword which is used for looping over an array or a collection of objects, strings, numbers, etc. Mainly, this loop is used in those situations where we need to work with one object at a time.

Syntax

The following block shows the syntax of Foreach loop:

In this syntax, <item> is a single value of a variable or an object which changes over each iteration. The <collection> is an array or a collection of numbers and strings which you want to access. When this loop executes, the PowerShell creates the variable $<item> automatically. There is a block in syntax which contains single or multiple statements which are executed for each item in a collection.

Flowchart of ForEach loop

PowerShell ForEach loop

Examples

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

Output:

1  2  3  4  5  6  7  8  9  10  

In this example, an array $Array is created and initialized with the integer values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The first time the Foreach statement executes, it assigns the integer value ‘1‘ of an array to the $number variable. Then, it uses the echo cmdlet to display the number 1. The next time through the loop, $number is set to 2, and so on. After the Foreach loop displays the number 10, PowerShell terminates the loop.

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

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)  

In this example, the foreach statement shows the list of items (files) which are returned by the get-childitem cmdlet.

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

Output:

apple  orange   guava  pomegranate  Mango  

Next TopicWhile loop

spot_img
Previous articleLearn MS Word Tutorial
Next articleWhat is PowerShell cmdlet