Save big (up to $1,875) on small business tools with our free membership, business.com+
Sign-Up Now
BDC Hamburger Icon

Menu

Close
BDC Logo
Search Icon
Search Icon
Advertising Disclosure
Close
Advertising Disclosure

Business.com aims to help business owners make informed decisions to support and grow their companies. We research and recommend products and services suitable for various business types, investing thousands of hours each year in this process.

As a business, we need to generate revenue to sustain our content. We have financial relationships with some companies we cover, earning commissions when readers purchase from our partners or share information about their needs. These relationships do not dictate our advice and recommendations. Our editorial team independently evaluates and recommends products and services based on their research and expertise. Learn more about our process and partners here.

How to Write a PowerShell “for” Loop (Windows PowerShell)

Learn how to automate repetitive business tasks using PowerShell's "for," "foreach," "while" and other loop types.

Written by: Tim Ferrell, Senior WriterUpdated Sep 02, 2025
Shari Weiss,Senior Editor
Business.com earns commissions from some listed providers. Editorial Guidelines.
Table Of Contents Icon

Table of Contents

Open row

A PowerShell “for” loop is a core scripting tool that allows you to execute a block of code multiple times. Whether you’re automating system tasks or processing data, understanding how to write a “for” loop in Windows PowerShell — and how it compares to other types of PowerShell loops — will streamline your scripting and improve efficiency. In this PowerShell guide, we’ll explain how to use the “for” loop, “foreach” and “ForEach-Object” loops, and the “while,” “do-while” and “do-until” loops. We’ll also share expert-backed tips for making the most of these loop types and provide solutions to common pitfalls.

Did You Know?Did you know
In a 2024 CFO survey from Duke University and the Federal Reserve Banks of Richmond and Atlanta, roughly 65 percent of companies said implementing automation was a strategic priority. The vast majority said they were motivated to use automation to "enhance business processes."

Syntax of PowerShell “for” loop

Powershell loop script
This screenshot demonstrates a script for a “for” loop.

The “for” loop in PowerShell follows a specific syntax structure that makes it both powerful and easy to understand. “For” loops are typically used to prompt a computer to iterate through a set of commands a specified number of times, either to step through an array or object or to repeat the same block of code as needed. This script is useful when “you know exactly how many times you want to do something,” said Siva Padisetty, who worked on the development of PowerShell when he was a director at Microsoft in the early 2000s.

A “for” loop is constructed using three main components:

  • Initialization: Setting the value of a variable when the loop is entered
  • Condition: The condition on which the loop should be terminated
  • Increment/Decrement: An action to be performed against that variable each time through the loop

The basic syntax follows this pattern:

**For (initialization; condition; increment) {**

    **# Commands to execute**

**}**

The following example shows a basic “for” loop used to create a multiplication table:

For ($i=0; $i -le 10; $i++) {

“10 * $i = ” + (10 * $i)

}

You can use “for” loops to step through array values by setting the initial value to the initial index of the array and incrementally increasing the value until the array length is met. The array index is specified by placing the incremented variable inside square brackets immediately following the variable name, as shown in the following example:

$colors = @(“Red”,”Orange”,”Yellow”,”Green”,”Blue”,”Indigo”,”Violet”)

For ($i=0; $i -lt $colors.Length; $i++) {

$colors[$i]

}

How to use a loop in PowerShell

Using loops in PowerShell involves understanding the different loop types and selecting the appropriate one for your specific task. Several loop types are available, and, in many cases, more than one loop technique can be used effectively. You must determine the most efficient loop type for your needs from either a performance or code readability perspective.

To implement a loop in PowerShell:

  1. Identify what you want to repeat.
  2. Determine how many times or under what conditions the repetition should occur.
  3. Choose the appropriate loop type.
  4. Write the loop syntax with your specific commands.
  5. Test the loop with sample data before running it on production systems.
FYIDid you know
PowerShell was launched for Microsoft Windows in 2006 and has been available on macOS, Linux and other nix operating systems since 2016.

“for” loop with Windows PowerShell examples

Here are three realistic business scenarios demonstrating the practical use of “for” loops in PowerShell. Each example shows how “for” loops can automate everyday business tasks, saving time and reducing manual errors in daily operations.

Example 1: Processing employee records

This example demonstrates how to process payroll data for multiple employees systematically. The loop ensures that each employee record is handled consistently, reducing the risk of missed payments or data entry errors.

**# Process payroll data for 50 employees**

**$employeeCount = 50**

**For ($i = 1; $i -le $employeeCount; $i++) {**

    **Write-Host “Processing employee ID: $i”**

    **# Add payroll calculation logic here**

**}**

Example 2: Creating monthly reports

Financial departments often need to generate reports for each month of the year. This “for” loop automates the process of creating monthly reports, ensuring no months are skipped and maintaining consistent formatting.

**# Generate reports for 12 months**

**For ($month = 1; $month -le 12; $month++) {**

    **$monthName = (Get-Date -Month $month -Format “MMMM”)**

    **Write-Host “Generating report for $monthName”**

    **# Add report generation logic here**

**}**

Example 3: File processing with arrays

This example shows how to process files for different departments systematically. The loop iterates through a predefined array of department names, ensuring all departments receive equal processing attention.

**# Process multiple department files**

**$departments = @(“Sales”,”Marketing”,”HR”,”Finance”,”Operations”)**

**For ($i = 0; $i -lt $departments.Length; $i++) {**

    **Write-Host “Processing files for: $($departments[$i])”**

    **# Add file processing logic here**

**}**

Other PowerShell loop types: “foreach,” “ForEach-Object,” “while,” “do-while,” “do-until”

“foreach” loop

The “foreach” loop in PowerShell is a language construct that enables you to iterate through all the items in a collection and execute a block of code for each element. Unlike the “ForEach-Object” cmdlet described below, the “foreach” loop loads the entire collection into memory before processing, making it faster for in-memory collections but potentially more memory-intensive for large datasets.

The basic syntax of the “foreach” loop follows this pattern:

**foreach ($item in $collection) {**

    **# Code to execute for each item**

**}**

PowerShell automatically creates the “$item” variable when the “foreach” loop runs, setting it to each successive value in the collection. This approach is particularly effective when you need to process arrays, lists or other collections where you want to perform the same operation on each element.

This type of loop is ideal when you have a known list of items that need identical processing, such as updating employee records or processing customer orders. Here’s a practical business example showing how to process employee data with the “foreach” loop:

**$employees = @(“John Doe”, “Jane Smith”, “Bob Johnson”)**

**foreach ($employee in $employees) {**

    **Write-Host “Processing payroll for: $employee”**

    **# Add payroll processing logic here**

**}**

The “foreach” loop excels in scenarios where you have a known collection and need to perform consistent operations on each item, such as processing files in a directory or updating database records. It’s generally faster than “ForEach-Object” for smaller collections since it processes the entire collection in memory.

Did You Know?Did you know
Because loops perform consistent acts on a given set of data, you can use PowerShell to sync folders and files with the "ForEach" loop.

“foreach-object” loop

PowerShell screenshot
In the image above, the code shows a ForEach-Object loop.

The “ForEach-Object” loop is valuable when you want the same computer task repeated for each item in a set.

“Imagine you have a basket of different fruits: an apple, a banana and an orange. You want to take each fruit out one at a time and take a bite,” Padisetty said. “The ‘ForEach-Object’ loop is like saying, ‘For each fruit in my basket, I’ll take it out and take a bite.'”

In many cases, using the “ForEach-Object” cmdlet is the best way to loop through an object. In its simplest form, “ForEach-Object” requires only an object to be looped through and a script block containing the commands to be performed on each member of the object.

These parameters can be specified either by the “-InputObject” and “-Process” parameter names or by piping the object to the “ForEach-Object” cmdlet and placing the script block as the first parameter. To illustrate this basic syntax, the following example shows two methods of using “ForEach-Object” to loop through the contents of a user’s documents folder:

$myDocuments = Get-ChildItem 

$env:USERPROFILEDocuments -File

$myDocuments | ForEach-Object {$_.FullName}

ForEach-Object -InputObject 

$myDocuments -Process {$_.FullName}

In certain scenarios, it may be beneficial to perform one or more actions just before or just after the loop is performed. The “-Begin” and “-End” parameters can be used to define script blocks to execute just before or after the contents of the “-Process” script block. This can be used to set or modify a variable before or after the execution of the loop.

“While,” “do-while” and “do-until” loops

Powershell While-loop
The script in this image is coded with the “while” loop.

Another type of loop PowerShell supports involves setting a condition that allows the loop to process either as long as the condition is true or until it is met. Both “while” and “do-while” loops are used to perform a computer action while the condition evaluates to “$true,” and they differ only in their syntax. “Do-until” loops have a similar syntax to “do-while” loops, but they stop processing once the condition statement is met.

Both “do-while” and “do-until” loops begin with the “do” keyword prefacing a script block and are followed by the condition keyword (“while” or “until”) and the condition. As an example, the following two loops function identically; only the condition is reversed:

$i=1

Do {

$i

$i++

}

While ($i -le 10)

 

$i=1

Do {

$i

$i++

}

Until ($i -gt 10)

Although “while” loops and “do-while” loops perform identically, the syntax is altered slightly. “While” loops use only the “while” keyword, followed by the condition and the script block. This loop is identical in function to the preceding examples, and it uses the same condition as the “do-while” loop:

$i=1

While ($i -le 10)

{

$i

$i++

}

Any of these three loop types — “while,” “do-while” and “do-until” — can also be used to loop indefinitely; the “while” and “do-while” loops with the condition set to “$true” and “do-until” loops with the condition set to “$false.”

“The key difference from ‘do-while’ is that ‘do-until’ keeps going until something becomes true, while ‘do-while’ keeps going as long as something is true,” Padisetty said.

In some situations, you may need to exit a loop early based on something other than the loop’s condition. In that case, the “break” keyword can be invoked to exit the loop. This example shows the same functionality, but it uses an infinite loop and the “break” keyword to exit at the appropriate time:

$i=1

While ($true)

{

$i

$i++

if ($i -gt 10) {

Break

}

}

TipBottom line
By wrapping your loops and other codes within functions, you can create and use modules in PowerShell to make your scripts more organized and easier to maintain.

When to use “for” loop vs. other loop types

Which PowerShell loop you should use depends on what you’re trying to accomplish. Padisetty shared the circumstances in which each loop is most appropriate.

Loop

When to use it

for

Use when you know exactly how many times you want the computer to do something.

foreach

Use when you have a collection of items and want to process each one with the same operation.

ForEach-Object

Use when you have a specific group of things and you want the computer to do something with each one.

while

Use when you want the computer to keep doing something as long as a condition is true.

do-while

Use when you want the computer to make sure it does something at least once and then keep doing it if a condition is true.

do-until

Use when you want the computer to keep doing something until a condition becomes true.

Use cases and best practices for Windows PowerShell loop scripts

Effective PowerShell scripting requires understanding not just how loops work but also when to use each type and how to implement them efficiently in your business. These use cases and best practices will help you write more robust, maintainable loop-based scripts for your company’s automation needs.

Use cases for PowerShell loops

PowerShell loops are particularly helpful in numerous business scenarios where repetitive tasks need automation. These common use cases demonstrate how loops transform time-consuming manual processes into efficient automated workflows.

File management and organization

Businesses often need to organize thousands of files based on date, size or other criteria. This “foreach” loop demonstrates how to automatically sort files into organized folder structures, eliminating hours of manual file management.

**# Organize files by date**

**Get-ChildItem “C:\Documents” | ForEach-Object {**

    **$yearMonth = $_.LastWriteTime.ToString(“yyyy-MM”)**

    **# Move files to organized folders**

**}**

Data processing and reporting

Monthly sales reporting can be automated using “for” loops to ensure consistent formatting and complete coverage of all time periods. This approach eliminates the risk of missing months or inconsistent report structures.

**# Process monthly sales data**

**For ($month = 1; $month -le 12; $month++) {**

    **# Calculate monthly totals and generate reports**

    **Write-Host “Processing month $month sales data”**

**}**

System administration tasks

IT departments can use “ForEach-Object” loops to monitor multiple servers simultaneously, ensuring consistent health checks across entire server farms without manual intervention.

**# Monitor server health across multiple systems**

**$servers = @(“Server1”, “Server2”, “Server3”)**

**$servers | ForEach-Object {**

    **# Check disk space, memory usage, and services**

    **Write-Host “Checking health of $_”**

**}**

Database operations

Database administrators can automate backup procedures for multiple databases, ensuring no databases are missed and all backups follow the same naming conventions and storage locations.

**# Backup multiple databases**

**$databases = Get-SqlDatabase**

**$databases | ForEach-Object {**

    **# Create backup for each database**

    **Write-Host “Backing up database: $($_.Name)”**

**}**

TipBottom line
Popular business tools, such as the best POS systems and highly rated accounting software, often have APIs that can connect to PowerShell. You can capitalize on that integration by, for example, using PowerShell to fetch or update data from the connected platform.

Best practices for using loops in PowerShell

Follow these guidelines to create efficient and maintainable PowerShell loops that perform reliably in business environments:

1. Choose the right loop type.

  • Use “for” loops when you know the exact number of iterations.
  • Use “foreach” for processing collections where you need all items in memory.
  • Use “ForEach-Object” for processing collections or arrays through pipelines.
  • Use “while” loops for condition-based iterations.

2. Optimize performance.

  • Minimize operations inside the loop.
  • Use pipeline processing when possible.
  • Avoid unnecessary variable assignments within loops.

3. Include error handling.

Always incorporate error handling within your loops to prevent script failures and provide meaningful feedback when issues occur. For example:

**ForEach-Object {**

    **try {**

        **# Loop operations here**

    **}**

    **catch {**

        **Write-Error “Error processing item: $_”**

    **}**

**}**

4. Use meaningful variable names.

    • Avoid generic names like “$i” and “$x.”
    • Use descriptive names that explain the loop’s purpose, such as “$service” and “$report.”

    5. Add comments and documentation.

      • Explain the loop’s purpose and expected behavior.
      • Document any complex logic within the loop.

      6. Test with small data sets first.

        • Verify loop logic before processing large datasets.
        • Use the “-WhatIf” parameter when available for testing.

        Common loop mistakes and debugging tips

        Understanding and avoiding common pitfalls can save significant time and prevent system issues. Here are issues you may encounter and how to solve them:

        Infinite loops

        • Problem: Loop conditions that never become false
        • Solution: Always verify your exit conditions and include safety counters.

        **# Bad: Infinite loop**

        **While ($true) {**

            **# Missing break condition**

        **}**

         

        **# Good: Safe loop with exit condition**

        **$counter = 0**

        **While ($condition -and $counter -lt 1000) {**

            **$counter++**

            **# Loop logic here**

        **}**

        Off-by-one errors

        • Problem: Loop runs one time too many or too few.
        • Solution: Carefully check your initialization and termination conditions.

        **# Common mistake: Missing the last item**

        **For ($i = 0; $i -lt $array.Length – 1; $i++) {**

        **# Correct: Process all items**

        **For ($i = 0; $i -lt $array.Length; $i++) {**

        Memory issues with large datasets

        • Problem: Processing too much data at once
        • Solution: Use streaming and batch processing.

        **# Instead of loading everything into memory**

        **Get-ChildItem -Path “C:\LargeFolder” | ForEach-Object {**

            **# Process one file at a time**

        **}**

        Debugging tips

        • Use “write-host” or “write-output” to track loop progress: Add these commands inside your loops to display current values, iteration counts or processing status. This helps you identify where loops might be failing or performing unexpectedly.
        • Add breakpoints in PowerShell ISE for step-by-step debugging: Set breakpoints on specific lines within your loop to pause execution and examine variable values at each iteration. This lets you step through the code line by line and identify logical errors.
        • Use the “-Verbose” parameter to see detailed execution information: Many PowerShell cmdlets support verbose output that shows additional details about what’s happening during execution. This extra information can help you understand why loops aren’t producing expected results.
        • Test loops with small sample datasets before full implementation: Start with a subset of your data (like the first 10 items) to verify your loop logic works correctly. This prevents long wait times and makes it easier to spot issues before processing large collections.

        Code formatting tips for editors

        When presenting PowerShell loop code in articles or documentation, proper formatting enhances readability and SEO performance:

        1. Use <pre><code> tags or markdown backticks.

        <pre><code class=”language-powershell”>

        # Loop from 1 to 5

        for ($i = 1; $i -le 5; $i++) {

            Write-Host “Number $i”

        }

        </code></pre>

        2. Format markdown code blocks with triple backticks and language specification.

        <pre><code>“`powershell 

        # PowerShell for loop 

        for ($i = 0; $i -lt 10; $i++) { 

        Write-Host $i 

        “`</code></pre>

        3. If no code block exists, paste the code in a paragraph and apply:

        • Monospace font
        • Light gray background
        • Padding for visual clarity

        4. Label code blocks with titles.

        • Example: PowerShell for loop processing array
        • Add comments in code for better readability and SEO.

        5. Follow these style conventions for consistency and readability:

        • Use consistent indentation — four spaces is recommended.
        • Include descriptive comments for complex operations.
        • Break long lines for better readability.
        • Use meaningful variable names in examples.

        FAQs: PowerShell Loop Types

        PowerShell is an open-source scripting language used to design efficient scripts and tools to assist people in their daily computer tasks. "PowerShell is like a special notebook where you can write instructions for your computer," said Siva Padisetty, a former PowerShell developer at Microsoft. "It was created by Microsoft to help people talk to their computers in a more powerful way than just clicking around with a mouse." Padisetty, who is now the chief technology officer at New Relic, gave this example to demonstrate how PowerShell works: "If using your computer with a mouse is like pointing at things you want, PowerShell is like being able to say, 'Please organize all my photos by date, put them in folders named by month and delete any duplicates.' That's a lot to do with just pointing and clicking, but with PowerShell, you can write instructions and the computer follows them perfectly every time."
        PowerShell has two primary functions: a command-line shell similar to the Windows command prompt (known as "cmd.exe") and a robust scripting language that can be molded to automate practically any computer task. Much like other operating system programs, PowerShell has binary commands to execute most actions. For example, you can run commands to read files, ping computers and remove registry keys. PowerShell also includes cmdlets, which are compiled binaries that allow users to build the tools necessary for their scripts. PowerShell follows a verb-noun syntax, in which command names always start with verbs and have a hyphen in the middle and a noun at the end. The verbs describe the action the cmdlet will perform. "Copy-item" copies a file, for example, and "get-content" gets text from a file. To learn more about how PowerShell works, check out our guide to functions in PowerShell and installing Windows patches with PowerShell.
        PowerShell loops, at their most basic, simply repeat a set of commands a certain number of times. Loops can simplify scripts and build interactive user menus; they're ideal for instructing your computer to perform consistent actions for a set period of time or a certain number of records. "It's a way to repeat the same action over and over without having to write the same instruction again and again," Padisetty said, comparing a loop to "having a super-efficient helper who will keep doing the same task until you tell them to stop or until they've finished everything."
        PowerShell supports several types of loops, each designed for specific scenarios:
        • for loop: Best for situations where you know exactly how many iterations you need
        • foreach loop: Used when you have a collection of items in memory and want to process each one with the same operation
        • ForEach-Object loop: Ideal for processing each item in a collection through the pipeline, especially with large datasets
        • while loop: Used when you want to continue looping as long as a condition remains true
        • do-while loop: Ensures the loop runs at least once before checking the condition
        • do-until loop: Continues looping until a specific condition becomes true
        Each loop type offers unique advantages depending on your specific automation needs and the structure of your data.
        Every modern business relies on computer operations to some extent, so you should use PowerShell and loops to optimize those operations. With PowerShell and loops, you can:
        • Increase efficiency: PowerShell uses the power of automation to cut down on the time and labor required to accomplish repetitive computer tasks. "Instead of doing the same task over and over manually, businesses can write it once and let the computer repeat it perfectly," Padisetty said. Plus, in addition to automating the task itself, you can set a schedule for the script to run automatically. Together, these efficiencies save not only time but also money.
        • Ensure accuracy and consistency: "When people do repetitive tasks, they might make mistakes or do things slightly differently each time," Padisetty said. "PowerShell will do exactly the same thing every time, exactly the way you told it to."
        • Scale your business: The more your company expands, the more demand there is on your processes to keep up. No need to worry: "Whether you need to update 10 files or 10,000 files, the same loop can handle it," Padisetty said. "As your business grows, your PowerShell scripts grow with you without requiring more effort."
        • Have more control: You may already be familiar with the benefits of workflow automation if you use business tools like high-quality CRM software. Those solutions, however, often have limitations when it comes to the parameters you can set. PowerShell loops give you much greater freedom and control, allowing you to automate data entry, process large data sets on a scheduled basis and integrate various systems exactly the way you want.
        The business uses of PowerShell and loops are virtually endless. You can set up scripts to automatically archive files, sync payroll data or organize shipping addresses, just to name a few. The less time you and your staff spend on those repetitive, mundane tasks, the more time you have to think and act strategically to grow the business.

        Mark Fairlie and Sean Peek contributed to this article. Source interviews were conducted for a previous version of this article. 

        Did you find this content helpful?
        Verified CheckThank you for your feedback!
        Written by: Tim Ferrell, Senior Writer