EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell ForEach Loop
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

PowerShell ForEach Loop

By Priya PedamkarPriya Pedamkar

powershell foreach loop

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

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,060 ratings)

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:

PowerShell ForEach Loop 1

Flow Diagram for PowerShell ForEach Loop

Below is the Flow diagram for PowerShell ForEach Loop:

powershell flow diagram

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:

PowerShell ForEach Loop 2

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:

powershell3

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.

powershell4

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.

powershell5

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:

powershell6

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 –

  1. For Loop in R
  2. What is PowerShell
  3. Uses Of Powershell
  4. How To Install PowerShell
  5. Array in PowerShell | Examples
  6. Guide to Powershell Write-Host
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
2 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more