C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ForEach loopThe 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. SyntaxThe following block shows the syntax of Foreach loop: Foreach($ 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 loopExamplesExample1: The following example displays the value of an array using 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 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: 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) 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: PS C:\> $fruits= "apple", "orange", "guava", "pomegranate", "Mango" PS C:\> foreach ($item in $fruits) >> { >> echo $item >> } Output: apple orange guava pomegranate Mango
Next TopicWhile loop
|