Download AttuneOps LogoAttuneOps CE for free Automate your system admin tasks

Download
  • Automated OS Installation
  • Virtual Host APIs
  • Centralised Scheduler
  • Script Automation
  • Document Generation
  • Rapid Automation Development
  • Portable Blueprint

Introduction to PowerShell Loops: For, Foreach, While & Do Loops

If you’re writing scripts in PowerShell, there is going to be some level of repetition involved. Whether your script manages users, processes files, monitors services, or automates administrative tasks, you’re probably going to execute the same block of code multiple times. This is where the benefits of fusing loops in PowerShell come into play.

The various types of PowerShell loops (For, Foreach, ForEach-Object, While, Do While, and DO Until) allow you to execute a block of code many times, based on either a counter value, a collection or a condition.

In this article, we will cover what PowerShell loops are, the purpose of each looping construct and how to use them correctly, including examples.

So, by the end, you should understand how to choose which looping construct to use in your scripts and how to avoid common mistakes.

PowerShell Loops

What Are PowerShell Loops?

Loops in PowerShell are flow control constructs that execute blocks of code repeatedly until a condition is satisfied or the collection to be processed is dealt with. They are essential elements for automation and consistency.

Why loops are important in PowerShell scripting

Loops are the backbone of automation. Without loops, scripts would be long, repetitive, and a pain to maintain. Loops allow you to:

  • Automate routine administrative activities
  • Do parallel processing for large data sets.
  • Reduce manual efforts and human errors
  • Write dynamic, scalable scripts

Instead of copying the same command 100 times, a loop lets PowerShell do that work for you.

Common use cases of loops in automation and administration

Loops in PowerShell have broad applications in the real world for IT, including:

  • Creation or administration of several user accounts
  • Checking repeatedly for system health or the status of services
  • Bulk processing of files and folders
  • Log monitoring or system performance monitoring
  • Running tasks until a condition is satisfied

Types of PowerShell Loops

PowerShell offers various kinds of loops in order to manage different scripting requirements.

Overview of different loop types in PowerShell

The basic types of loops in PowerShell are:

  • For Loop: Ideal for running a block of code a predetermined number of times.
  • Foreach Loop: This kind of loop accesses each element in the collection.
  • ForEach-Object: Piped-based processing
  • While Loop: Executes repeatedly as long as the condition remains true.
  • Do While Loop: Executes at least one time before checking for the condition.
  • Do Until Loop: The loop runs until a condition becomes true.

Each type of loop has its own use, and using the suitable one will optimise the script’s speed and readability.

For Loop in PowerShell

Syntax of the For Loop

for ($i = 0; $i -lt 10; $i++) {
# Code to execute
}

The for loop has three parts:

  • Initialisation: $i = 0 (starting value)
  • Condition: $i -It 10 (loop runs while true)
  • Increment: $i++ (updates counter after each iteration)

Simple for loop example

for ($i = 1; $i -le 5; $i++) {
Write-Output "Count: $i"
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

This loop runs exactly five times, printing the counter value during each iteration.

When to use a for loop

You can use a for loop when you have a known number of iterations ahead of time. The most common use of a for loop would include:

  • Counting from 1 to 100
  • Handling a fixed range of numbers
  • Running a task a specific number of times.

It’s efficient, predictable, and easy to control.

Foreach Loop in PowerShell

Difference between For Loop and Foreach loop

The foreach loop is meant for use with collections such as arrays and lists. This loop automatically manages the iteration and does not require indexing.

For loop: More suited for numeric counters; with foreach, you do not have to think about index numbers or lengths of a collection.

Foreach: Best for collections

Foreach loop syntax with arrays

$fruits = @("Apple", "Banana", "Orange")
foreach ($fruit in $fruits) {
    Write-Output "Fruit: $fruit"
}

Example of Foreach loop with arrays

Output:

Fruit: Apple
Fruit: Banana
Fruit: Orange

This ensures that it is one of the most straightforward and easy-to-read loop types within PowerShell.

ForEach-Object in PowerShell

What is the ForEach-Object cmdlet?

The ForEach-Object cmdlet allows you to process items being sent through the pipeline in PowerShell. You can also use the alias “%”.

Whereas “Foreach” will process an item from your collection at once and store the entire collection in your memory. ForEach-Object processes only a single object and doesn’t load all the data into memory simultaneously.

Foreach Loop vs ForEach-Object

Foreach Loop

  • Used primarily with small to medium lists
  • Loads an entire collection into memory.

ForEach-Object

  • Processes objects in sequence
  • Uses less memory
  • Processes are slightly slower because of any overhead caused by the pipeline.

ForEach-Object is a perfect fit for working with very large collections of data or in situations where data will be streamed to your application from a different source.

Real-world example using a pipeline

Get-Process | ForEach-Object {
    Write-Output "Process: $($_.Name) - ID: $($_.Id)"
}

This efficiently lists all running processes while streaming data through the pipeline.

While Loop in PowerShell

While loop syntax

while ($condition) {
    # Code to execute while condition is true
}

Example of a while loop

$i = 1
while ($i -le 5) {
    Write-Output "Count: $i"
    $i++
}

The loop continues until $i exceeds 5.

Common scenarios for the while loop

Use a while loop when there is an unspecified number of iterations based on a condition, such as:

  • Waiting for user input
  • Observing the system state
  • Retrying an Operation until it succeeds.

Do While Loop in PowerShell

How Do While loop works

A Do While loop will execute the code block and then evaluate the condition. So, it would be executed at least once.

Syntax and example

do {
    # Code to execute
} while ($condition)

Difference between While and Do While

  • While: checks condition first (may not run at all)
  • Do While: Runs once before checking the condition

This is useful when at least one execution is required.

Do Until Loop in PowerShell

Do Until loop syntax

do {
    # Code to execute
} until ($condition)

Example of Do Until loop

$i = 1
do {
    Write-Output "Count: $i"
    $i++
} until ($i -gt 5)

When to use Do Until loop

Do Until is used when you want the execution to continue until a condition turns true. It’s essentially the opposite of Do While, in that it still guarantees at least a single execution.

PowerShell Loop Control Statements

Using Break in loops

The break statement exits the loop immediately.

for ($i = 1; $i -le 10; $i++) {
if ($i -eq 5) { break }
Write-Output $i
}

Outpost stops at 4.

Using Continue in loops

The break statement exits the loop immediately.

for ($i = 1; $i -le 5; $i++) {
if ($i -eq 3) { continue }
Write-Output $i
}

Output: 1, 2, 4, 5

Choosing the Right Loop in PowerShell

LoopWhen it checksRuns once for sure?Best for
ForBeforeYesKnown number of repeats
ForeachN/AYesWorking with arrays or lists
ForEach-ObjectN/AYesPipeline or large data
WhileBeforeNoRepeating until a condition
Do WhileAfterYesMust run at least once
Do UntilAfterYesStop when condition is true

Best practices for loop usage

  • Choose loops based on iteration type
  • Prefer foreach over for in terms of clarity and speed.
  • Use ForEach-Object for large pipelines
  • Variables must be initialised only once.
  • Keep loop logic simple and readable.

Common Mistakes to Avoid with PowerShell Loops

Infinite loops

Infinite loops arise when the condition in a while statement never changes

Example

While (true) { }

Always update counters or use break statements to avoid runaway scripts.

Performance issues in large datasets

Large data loads to foreach can cause memory to be loaded. Use ForEach-Object and filter early with where-object to improve efficiency.

Frequently Asked Questions

How to stop a PowerShell loop?

A PowerShell loop can also be stopped at any time using a break statement within the loop. If the break command is encountered in PowerShell, it forces the execution to leave the loop immediately and moves to the rest of the script commands to be executed.

How to make an infinite loop in PowerShell?

Infinite loops can also be made by using while ($true) { } or do { } while ($true), wherein the condition will always return TRUE. These will run infinitely until they are manually interrupted.

Is foreach or for faster?

The foreach statement will perform better and will be easier to understand when working with data structures stored entirely in memory, like arrays and/or lists, because of lower overhead costs. The for loop will work well with numbers and counters. For bigger data and/or pipeline inputs, it will be more memory-efficient, even though it will run a little slower because it processes pipelines.

Conclusion

PowerShell loops offer great functionalities in making an automation process efficient, feasible, and manageable. To master programming loops in PowerShell, you must understand the differences between For loops, Foreach, ForEach-Object, While, Do While, and Do Until loops, so that you can develop efficient scripts that offer great performance.

Post Written by
Shivam Mahajan
Shivam Mahajan
Shivam Mahajan is an editor skilled in SysOps, Tech, and Cloud. With experience at AttuneOps and other companies, he simplifies complex technical material for easy understanding.

Comments

Join the discussion!