Updated March 23, 2023
Introduction to PowerShell ForEach Loop
Understanding ForEach Loop in PowerShell, ForEach and forLoop both performing the same tasks, both of them are for manipulating and executing the same piece of code on a repetitive basis. If you are reading each element of an array or it may be reading each line of a file, in such type of condition we use foreach. For example, an array containing users and we want to check the user with the name “Vijay”, so we need to check each element and for that, we need a “foreach” loop and once user “Vijay” found loop will exit. If you needed to look at the city attribute of each user before taking an action, you could use ForEach Loop and you can perform respective work on each city.ForEach saves little memory and time as compared to for loop. In PowerShell 4.0 and later version, the ForEach Method provides even faster performance.
Syntax of ForEach Loop
Below is the syntax
foreach ($<item> in $<Actualarray>)
{
<statement 1>
<statement 2>
<statement 3>
<statement ...>
}
In the above syntax, we can see, every time one item from the Actualarray will be picked and that item will go for processing inside the foreach loop. If $<Actualarray> is blank or having no item inside it, it will not go for the execution of statements. PowerShell creates the variable $<item> automatically when the Foreach loop runs. For example, the Foreach loop in the following example displays the values in the $students array. In for loop, we needed to write logic to check if the array is empty or not, the foreach loop executes statements block if there is any element inside array.
Code:
$students = ""
PS /home/ranjan> foreach ($student in $students)
{
Write-Host $student
}
output nothing, which means checking of array elements attributes are done internally by foreach loops.
$students = "ajay","vijay","ranjan","akash",”vikash”
foreach ($student in $students)
{
Write-Host $student
}
Output and Code Screens:
Flow Diagram for PowerShell ForEach Loop
Below is the Flow diagram for PowerShell ForEach Loop:
Explanation of the above flow Diagram: The above flow diagram very clearly represents flow, Once execution starts first, it will check for data(checking if the element is there in the array) if it’s empty loop will halt. But if Data is there it will continue execution and execute statement 1, statement 2, statement 3 till last data of array. Once Array get empty loop stop execution.
Output:
Explanation of the above output: Above screen shows, if there were two attributes inside array it was printing two times, hello, but if we made $students as an empty array no hello print, that means in case of any attribute is available inside $students array than it is going to execute statement block else it is not executing.
How does ForEach Loop work in PowerShell?
Suppose we have 4 elements and we want to multiply each number with five. Suppose we have $a,$b,$c,$d and we have to multiply each with 5 so what we will do, look below example:
Sample Code:
$a=2 ,$b=4,$c=9,$d=5
$a * 5 =10,$b * $5=20 ,$c * 5=45,$d*5=25
Hence we got our result. But it was good till we have only 4 items to multiply with 5, suppose there will be 10000 elements which need to multiply with 5 then it would be a very tedious task to write for each.
So what would be an easy solution for it? All we need to do is, we should create an array with all our elements and pass the array by foreach and multiply every element with 5. To multiply the number five to each of the elements in the array, We need to walk through the array by using the ForEach command.
Here’s the Entire Script:
Code:
$a = 2 ,$b = 4 ,$c = 9 ,$d =5
$f = $a,$b,$c,$d
Foreach ($i in $f)
{
$i * 5
}
Output:
Explanation of the above code: In the above examples we can see, we defined one another variable $f and assigned all 4 variables to it, which makes it an array. Finally, we pass it from the foreach loop which given us a result of 10,20,45,25. This way we are making our life easier, as in real life there would be lakhs of record which need to modify, so we can not do it one by one so we are using the foreach loop to deal with these. Just run once and modify as many as the record you want.
Examples in PowerShell ForEach Loop
Below is the example in PowerShell ForEach Loop:
Example #1
Loop through an array of strings containing students’ names and find the length of each string inside the array.
Code:
$students = @("Ranjan","Ajay",”Vijay","Sujit","John","Rakesh",”Hari”)
foreach ($student in $students) {
"$student = " + $student.length
}
Output: Ranjan = 6, Ajay = 4,Vijay = 5, Sujit = 5, John = 4 ,Rakesh = 6, Hari = 4.
Example #2
Let me give you one real-life example, In examinations, you have seen 30 marks out of 100 used to be pass marks. So suppose there are laks of student and there is one rule if any student gets 27 marks give him 30 marks, that means just add 3 marks extra in his 27 marks. So we Loop through an array of students marks and add 3 marks if their marks are 27 and let them pass in examinations as 30 marks are pass marks.
Code:
$marks =@(34,39,49,12,27,80,23,88,27)
foreach ($mark in $marks) {
if ($mark -eq 27) { $mark+3 } else{ $num}
}
Output: There were two students but checking manually in lakhs of students for 27 marks was a bit tedious task which we solved.
Example #3
One another example, Find all numbers between 1 to 100 which are completely divisible by 10.
Code:
$numbers =@(1..100)
foreach ($number in $numbers)
{
if ( -not ($number % 10) )
{
"$number is totally divisible by 10"
}
}
10 is totally divisible by 10
20 is totally divisible by 10
30 is totally divisible by 10
40 is totally divisible by 10
50 is totally divisible by 10
60 is totally divisible by 10
70 is totally divisible by 10
80 is totally divisible by 10
90 is totally divisible by 10
100 is totally divisible by 10
Output:
Conclusion
To conclude, a foreach loop statement allows us to execute a statement or group of statements multiple times along with checking element availability in the array that means run the next statement if there are any elements. Foreach loops run only if there are any elements inside the array, which makes it different than for loop.
Recommended Articles
This is a guide to PowerShell ForEach Loop. Here we discuss How does ForEach Loop work in PowerShell? , with different examples. You can also go through our other related articles to learn more –