EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Loops in PowerShell
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

Loops in PowerShell

By Priya PedamkarPriya Pedamkar

Loops in PowerShell

Introduction to Loops in PowerShell

We will always need loops if we have something repetitive work, In loop, we run a piece of code or any statement on a repetitive basis. One real example, suppose in a school there are 20000 students and because of some reason, the university decided to give 5 marks extra for examinations to every student. So the university has decided to give these 5 marks to every student except those whose attendance is less than 100 days. Now you just assume how staff will do it, they will have to check every student’s marks and attendance of the year. But Same thing with the help of Any loop it could have been done very easily, by creating an array of students with their marks and attendance dates. Hereby using a loop we are able to save extra efforts. Let us understand Loops in PowerShell in detail.

Types of  Loops in PowerShell

There are many ways to run loop in PowerShell, but it always depends on your requirements and feasibility of the program, for example, if you want to execute at least once for any array than we should use do-while loop else there are for loop and for each which are good.

Types and their examples are given below:

Types of  Loops in PowerShell

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. While

While statement takes a condition as argument and execution of statement inside a while loop depends on the condition, that means if a condition is a success then it will execute statement else not.

Syntax:

while(condition)
{
Statement 1
Statement 2
….
}

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,650 ratings)

Example:

$j = 0
while($j -lt 10)
{
Write-Output $j
$j++ }

Below is the screen for above code execution

output

2. Do While

Do while is similar to while loop only difference is it will execute at least once, that means it will execute do a block for the first time and while block if a condition is true. In the below syntax do block executed for the first time for sure.

  • Do: This block executes for first and once when execution starts.
  • While: Execution of statement 1 and statement 2 totally depends on the success of the condition.

Syntax:

Do
{
Statement 1
Statement 2
….}while(condition){
Statement 3
Statement 4
…..
}

Example #1:

$j = 0
do
{
Write-Output $j  // this block will execute first time
$j++
}while($j -lt 10)

Example #2:

In this example do block will execute for the first time even condition was not true.

$j = 0
do
{
Write-Output $j
$j--
}while($j -gt 0)

The screen for both programs is shown below

Do While Example

3. Do Until

Do until is little different than do while, in do until the execution will continue till return negative result by “until block”.two things are major here.

  • Do: This block will keep executing until the block condition gets failed, which means until the block return a negative value.
  • Until: Do block statement 1 and statement 2 execute until conditions return negative results.

Syntax:

do
{
Statement 1
Statement 2
….
}until(condition)

Example:

$i = 0
do
{
Write-Output $i
$i++
}until($i -ge 5) //keep checking condition

In “do until” block we can see the execution of do block will continue till the “until block” condition is returning a positive value.

Below is the screen for above code execution

Do Until

4. For

For statement runs a statement list zero or more times based on an initial setting. In the below syntax of for loop, there are three important sections

  • Initialization section: In this section, it assigned initial value for any variable, this section runs once for the first time.
  • Condition: In condition parts, we write our condition for which loop will run, which means the execution of statement block always depends on the success of condition parts if the condition is true then statement block will execute else not.
  • Operation: In this block, we can increase, decrease or change the value of the initializing a variable or any things according to our requirements.

Syntax:

for($initialisation; condition; operation)
{
Statement 1
Statement 2
….
}

Example #1:

for($i = 0; $i -lt 3; $i++)
{
Write-Output $i
}

Output screen of above code

loops in poershell 4

Many times one for loop is not enough to complete our requirements, so we can use nested for loops. We should try to avoid nesting of loops as their time complexity may go very high if not handled properly. Below is an example of nested for loop .

Example #2:

for($j = 0; $j -lt 3; $j++)
{
$line = ''for($j = 0; $j -lt 3; $j++)
{
$line += $j.ToString() + $j.ToString() + '  '
}
Write-Output $line
}

Output: 00  11  22

loops in poershell 6 PNG

5. ForEach

“Foreach” runs statement blocks for consecutive time till the last item of an array. Good things about forEach statement is, we do not have to write any separate code to extract an array of items.In general “foreach” is a optimized version of “for” loop which giving inner item of array without writing any programs. Here, it simply checks for item inside array on which we are running “foreach” loop if any item is there it will execute statement 1 and statement 2 blocks.

Syntax:

foreach($arrayItems)
{
Statement 1
Statement 2
…..
}

Example:

$numbers = 23,21,22,78
foreach($number in $numbers)
{
“$number is now =“ +$number
}

Below screen show above executions

ForEach loops

Benefits of Loops in PowerShell

The biggest benefit of using a loop is, it reduces too much manual work also it is very good to control the big size of data for a similar type of activity on it. Let’s say I want you to print 1 to 1000000 and I told you that you can add 1 to every number divisible by 2, which is an even number. Then if you start printing one by one and try to add 1 to every even number it will take too much time. So, a better and easy way you suggested was just repeating this process of adding one to the number until we reach 1000000. The biggest benefit we are getting from loop is we are reusing the same piece of code, we do not require to write the same code for lakhs of data it will automatically execute code till the end.

Below are a few points of Benefits

  • Increase code reusability, which makes code smaller
  • The faster calculation for big data, saving a lot of manual labor
  • The redundancy of code is less.

An example with its benefits

Question: print upto 1000.

Without loop,
Write-Output 1;
Write-Output 2;
Write-Output 3;
Write-Output 4;
…so on
Till 100

With loop,
$x=1..100
foreach($y in $x){
Write-Output $y;
}

Recommended Articles

This has been a guide to Loops in PowerShell. Here we discuss types of Loops in PowerShell along with their benefit. And we discovered that loops are a very powerful tool with less effort to use the same code. You may also have a look at the following articles to learn more –

  1. What is Shell Scripting?
  2. PowerShell String Functions
  3. PowerShell Operators
  4. PowerShell Commands
  5. Examples of Array in PowerShell
  6. Function in Shell Scripting | Examples | Types
  7. Examples of Echo in Shell Scripting
  8. Complete Guide to Loops in Shell Scripting
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
1 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