Windows powershell for loop

Recently, while working on a PowerShell script, I was required to iterate over a block of code multiple times. For this, I used the for loop in PowerShell. In this tutorial, I will show you how to work with the PowerShell for loop with various examples.

What is a for loop in PowerShell?

A For loop in PowerShell is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. It consists of three main components: initialization, condition, and repetition.

The initialization step sets up a counter variable, the condition checks whether the loop should continue running, and the repetition step updates the counter variable after each iteration.

Syntax of the PowerShell For Loop

Below is the syntax of the For loop in PowerShell:

for (<Initialization>; <Condition>; <Repeat>)
{
    <Statement-Block>
}
  • The initialization (init) sets the starting point of the loop. This is where the loop variable is defined, typically with a value of zero.
  • The increment clause updates the loop variable each time the loop runs. For example, $i++ increments the variable by one.
  • The condition checks whether the loop should continue running. If the condition is true, the loop runs; if false, it stops. An example is [i -lt 10]. Together, these three parts control the loop’s execution.
  • Repeat: This part is executed at the end of each iteration. It is usually used to increment or update the counter variable.
  • Statement-Block: This is the block of code that you want to execute repeatedly as long as the condition is true.

Read PowerShell Do While Loop

Basic for loop Example in PowerShell

Let’s start with a simple example to print numbers from 1 to 5 using PowerShell for loop:

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

In this example:

  • Initialization$i = 1 sets the initial value of the counter variable $i to 1.
  • Condition$i -le 5 checks if $i is less than or equal to 5.
  • Repeat$i++ increments the value of $i by 1 after each iteration.
  • Statement-BlockWrite-Output $i prints the current value of $i.

You can see the output in the screenshot below:

Powershell for loop

Here is another little complex example where you want to iterate through a PowerShell array and perform some action on each element. Here is the complete PowerShell script.

$servers = @("Server1", "Server2", "Server3")

for ($i = 0; $i -lt $servers.Length; $i++)
{
    Write-Output "Pinging $($servers[$i])"
    Test-Connection -ComputerName $servers[$i] -Count 1
}

In this example:

  • Initialization$i = 0 initializes the counter variable $i to 0.
  • Condition$i -lt $servers.Length checks if $i is less than the length of the $servers array.
  • Repeat$i++ increments the value of $i by 1 after each iteration.
  • Statement-Block: The block pings each server in the array.

Read While Loop in PowerShell

Nested For Loop in PowerShell

There will be times when you might need to put loop inside a loop and that is known as nested loops in PowerShell. Here is an example where we are using a nested for loop in PowerShell.

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

This nested loop runs the inner loop each time the outer loop runs. Here is the output:

0, 0
0, 1
0, 2
1, 0
1, 1
1, 2
2, 0
2, 1
2, 2

Look at the screenshot below for the output, after I executed the above nested for loop PowerShell script.

Nested For Loops in PowerShell

Read PowerShell Do-Until Loop Examples

How to Use Break and Continue in PowerShell for loop?

Now, let me show you how to use the break and continue in PowerShell for loop.

Break and Continue statements give you control over loop execution.

  • break: Exits the for loop immediately.
  • continue: Skips the remaining statements in the current iteration and proceeds to the next iteration.

Here is an example of how to use the break statement in a for loop in PowerShell.

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

In this loop, it stops when $i equals 5. The continue statement skips the rest of the current loop iteration and proceeds with the next iteration.

Here is an example of how to use continue in PowerShell for loop.

for ($i = 0; $i -lt 10; $i++) {
    if ($i % 2 -eq 0) { continue }
    Write-Output $i
}

This loop skips even numbers, outputting only the odd ones.

You can see the output in the screenshot below, after I executed using VS code.

Break and Continue in PowerShell for loop

Here’s an example of how you can use the break and continue in a single PowerShell script.

for ($i = 1; $i -le 10; $i++)
{
    if ($i -eq 5)
    {
        continue  # Skip the rest of the loop when $i is 5
    }
    if ($i -eq 8)
    {
        break  # Exit the loop when $i is 8
    }
    Write-Output $i
}

In this example:

  • The loop skips printing the number 5 due to the continue statement.
  • The loop terminates when $i equals 8 due to the break statement.

Read How to Loop Through an Array in PowerShell?

PowerShell for loop try catch

Now, let me show you how to handle errors in a for loop in PowerShell using the try catch.

We can use the Try and Catch blocks within a For loop in PowerShell to handle exceptions gracefully. This is particularly useful when you want to ensure that the loop continues executing even if an error occurs during one of the iterations.

Syntax

The syntax for using Try and Catch within a For loop in PowerShell is like the below:

for (<Initialization>; <Condition>; <Repeat>)
{
    try
    {
        # Code that may throw an exception
    }
    catch
    {
        # Code to handle the exception
    }
}

Example

Now, let us see an example.

Suppose we attempt to divide a number by a series of values, including zero, which will throw an exception. We want to catch this exception and handle it without stopping the entire loop.

Here is the complete PowerShell script.

$numbers = @(10, 5, 0, 2)

for ($i = 0; $i -lt $numbers.Length; $i++)
{
    try
    {
        $result = 100 / $numbers[$i]
        Write-Output "Result of 100 divided by $($numbers[$i]) is $result"
    }
    catch
    {
        Write-Output "Cannot divide by $($numbers[$i]). Error: $_"
    }
}

In this example:

  • Initialization$i = 0 initializes the counter variable $i to 0.
  • Condition$i -lt $numbers.Length ensures the loop runs as long as $i is less than the length of the $numbers array.
  • Repeat$i++ increments the counter variable $i by 1 after each iteration.

Within the try block, we attempt to divide 100 by the current element of the $numbers array. If the division by zero occurs, it throws an exception, which is caught by the catch block. The catch block then outputs an error message indicating the issue.

I executed the above PowerShell script and you can see the output in the screenshot below:

PowerShell for loop try catch

Conclusion

I hope now you got to know how to use the for loop in PowerShell with various example. I have also shown you how to use the break and continue statement in a PowerShell for loop. Finally, we got to know how to use the try catch statements in a for loop in PowerShell with an example.

If you still have any question feel free to leave a comment below.

You may also like:

  • PowerShell ForEach Loop
  • How to Use Exclamation Mark in PowerShell If Statements?

Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.

PowerShell is a great tool for programmers and nonprogrammers alike. Its ability to automate both simple and complex coding is invaluable to businesses. To get the most out of PowerShell, you should take advantage of loops. The commands are essential to automating time-consuming, mundane computer tasks and improving operational efficiency.

In this PowerShell guide, we’ll explain how to use the For loop, ForEach-Object loop, and the While, Do-While and Do-Until loops. We also share the top reasons businesses should use PowerShell and loops, along with expert-backed tips for making the most of these codings.

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.”

What is PowerShell?

PowerShell is an open-source scripting language that’s 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, who worked on the development of PowerShell when he was a director at Microsoft in the early 2000s. “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.” 

How PowerShell works

PowerShell was originally created with the intention of being easy to understand, so it’s great for people who aren’t familiar with software programming. It has two primary functions: a command-line shell that is 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.

It was launched for Microsoft Windows in 2006, and PowerShell has been available on macOS, Linux and other *nix operating systems since 2016.

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.

What are loops in PowerShell?

PowerShell loops, at their most basic, simply repeat a set of commands a certain number of times. Ideal for instructing your computer to perform consistent actions for a set period of time or a certain number of records, loops can simplify scripts and build interactive user menus.

“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.”

There are several loop types available in PowerShell, and, in many cases, more than one loop technique can be used effectively. At times, you must determine the most efficient loop type, from either a performance or code readability perspective, for your needs. For the loops discussed in this article, we’ll explain when it’s best to use each of them.

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.

How to program with loops

Some of the most common loops are the For, ForEach-Object, and While, Do-While and Do-Until loops. Below we’ll explain what the loops are and how to program them.

For loop

Powershell loop script

This screenshot demonstrates a script for a For loop.

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,” Padisetty said.

A For loop is constructed by setting the value of a variable when the loop is entered, the condition on which the loop should be terminated and an action to be performed against that variable each time through the loop.

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]
}

ForEach-Object loop

PowerShell screenshot

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

The ForEach-Object is valuable when you want the same computer task to be 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.

ForEach-Object has two aliases — ForEach and % — and supports shorthand syntax beginning in PowerShell 3.0. The following three examples are identical in function even though the name of the loop differs:

Get-WMIObject Win32_LogicalDisk | ForEach-Object {$_.FreeSpace}

Get-WMIObject Win32_LogicalDisk | ForEach {$_.FreeSpace}

Get-WMIObject Win32_LogicalDisk | % FreeSpace

Because loops perform consistent acts on a given set of data, you can use PowerShell to sync folders and files with ForEach loop.

While, Do-While and Do-Until loops

Powershell While-loop

The script in this image is coded with the While loop.

The third 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 as 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 those three loop types — Do-While, Do-Until and While — can also be used to loop indefinitely. 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 final 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
}
}

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 each loop

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-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.

Why businesses should use PowerShell and loops

Every modern business relies on computer operations to some extent. Below, find out the top reasons companies should use PowerShell and loops to optimize those operations.

  • To 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.
  • To 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.”
  • 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.”
  • To 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 for 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.

Looping through a set of instructions until a certain condition is met is a fundamental concept in any programming language, and PowerShell is no exception. Loops in PowerShell, such as the for loop, foreach loop, and ForEach-Object cmdlet, provide a powerful way to process collections of objects, files, or any set of data.

In this blog post, you’ll learn the different types of loops available in PowerShell, see them in action through practical examples, and discover tips to leverage their full potential. Whether you need to perform an action a specific number of times, or iterate over objects until a condition is satisfied, PowerShell loops are the key to efficient scripting.

Take your PowerShell skills to the next level!

If you’re interested in learning PowerShell, then considering taking our PowerShell automation course at Server Academy:

Course: Administration and Automation with Windows PowerShell

Windows PowerShell helps you automate the management of Active Directory users, the management of VM…

The For Loop

PowerShell loops allow you to run a block of code a specified number of times. This allows you to reduce the amount of code you need to type since a loop is iterative in nature. The for loop, in particular, is a powerful iteration tool within PowerShell’s scripting arsenal, enabling precise control over how many times a set of commands is executed.

Here’s a simple breakdown of how a for loop works:

for ($i = 1; $i -le 10; $i++) {
    # Commands to be repeated
}

This code snippet demonstrates a basic for loop that runs from 1 to 10. The loop consists of three parts: initialization ($i = 1), condition ($i -le 10), and increment ($i++), all contributing to its cyclical execution.

Practical Examples of For Loops in PowerShell

Simple Counting: To illustrate, here’s how you could use a for loop to count from 1 to 10, outputting each number:

for ($i = 1; $i -le 10; $i++) {
    Write-Host $i
}

Array Processing: For loops shine in scenarios like iterating over arrays. For instance, if you have an array of server names you wish to check connectivity for:

$servers = @('Server1', 'Server2', 'Server3')
for ($i = 0; $i -lt $servers.Length; $i++) {
    Write-Host "Attempting to ping " + $servers[$i]
    Test-Connection -ComputerName $servers[$i] -Count 2
}

This script pings each server in the $servers array twice, utilizing the loop to move through the array elements systematically.

Nested For Loops: To tackle more intricate tasks, for loops can be nested within each other. Consider creating a multiplication table:

for ($i = 1; $i -le 10; $i++) {
    for ($j = 1; $j -le 10; $j++) {
        $result = $i * $j
        Write-Host "$i multiplied by $j equals $result"
    }
}

This generates a 10×10 multiplication table, demonstrating nested loops’ capability to handle complex data structures efficiently.

The for loop stands as a cornerstone in PowerShell scripting, adaptable to countless applications. From straightforward number sequencing to sophisticated data manipulation, its versatility is bound only by the scripter’s inventiveness.

Moving on to the next section, we’ll explore the ForEach loop:

The ForEach Loop

The ForEach loop presents a more intuitive approach to iterating over collections. Unlike the for loop, which requires explicit management of counters and conditions, ForEach simplifies the process, directly iterating over each element in a collection or array.

Here’s the basic structure of a ForEach loop:

foreach ($item in $collection) {
    # Commands to execute for each item
}

In this construct, $item represents the current element in $collection being processed. This setup is especially useful for dealing with collections where you’re less concerned about the index of each item and more focused on the items themselves.

Iterating Over Collections

Consider you have an array of file names and you wish to display each one. The ForEach loop makes this task straightforward:

$files = @('file1.txt', 'file2.txt', 'file3.txt')
foreach ($file in $files) {
    Write-Host "Processing file: $file"
    # Additional file processing logic here
}

This loop goes through each file name in the $files array, allowing you to perform operations like file analysis or manipulation on each one.

Applying ForEach for System Administration Tasks

System administrators find the ForEach loop particularly handy for executing commands across multiple system objects. For instance, restarting a list of services can be accomplished efficiently:

$services = @('Service1', 'Service2', 'Service3')
foreach ($service in $services) {
    Write-Host "Restarting $service..."
    Restart-Service -Name $service
}

This snippet iterates through each service in the $services array, executing the Restart-Service cmdlet for each, demonstrating the ForEach loop’s utility in operational scripts.

The Power of Simplicity

The ForEach loop is emblematic of PowerShell’s design philosophy—making complex tasks manageable through simple, readable syntax. Its ability to iterate over any collection without the need for manual index management or condition checking streamlines script development, making it a favorite among PowerShell scripters for its clarity and efficiency.

The ForEach-Object Cmdlet

Now, let’s pivot to another pivotal tool in PowerShell’s scripting toolkit: the ForEach-Object cmdlet. This cmdlet is a powerhouse in pipeline operations, allowing you to apply a script block to each item in a pipeline. It’s particularly valuable when working with a stream of data produced by other cmdlets.

Understanding ForEach-Object

The ForEach-Object cmdlet is invoked within a pipeline and operates on each object that flows through it. Its usage is straightforward yet profoundly impactful in processing collections of objects. Here’s the syntax:

Get-ChildItem | ForEach-Object {
    # Script block to execute for each object
}

In this example, Get-ChildItem retrieves items in the current directory, and ForEach-Object processes each item individually. This cmdlet embodies the essence of PowerShell’s pipeline efficiency, enabling operations on large sets of objects with minimal memory overhead.

Practical Use Cases of ForEach-Object

Modifying Objects: Imagine you need to append a string to the names of all files in a directory:

Get-ChildItem | ForEach-Object {
    Rename-Item $_ "$($_.Name)_backup"
}

This script appends _backup to each file name, illustrating how ForEach-Object facilitates direct manipulation of objects within a pipeline.

Filtering and Processing: Combining ForEach-Object with conditional logic allows for powerful data filtering and processing scenarios. For example, to find and display all large files within a directory:

Get-ChildItem | ForEach-Object {
    if ($_.Length -gt 10MB) {
        Write-Host "$($_.Name) is a large file."
    }
}

This snippet filters out files larger than 10MB, showcasing the cmdlet’s capability to handle complex filtering inline with processing.

Comparing ForEach Loop and ForEach-Object

While both the ForEach loop and ForEach-Object cmdlet serve the purpose of iterating over collections, their application contexts differ. The ForEach loop is typically used for iterating over arrays and collections stored in memory, providing a straightforward syntax for direct manipulation. On the other hand, ForEach-Object excels in processing streaming data from cmdlets in a pipeline, optimizing for memory usage and flexibility in handling objects.

The ForEach-Object cmdlet is a testament to PowerShell’s design, emphasizing pipeline efficiency and the ability to perform sophisticated operations on a sequence of objects. Its integration into scripts exemplifies PowerShell’s capacity for crafting concise, yet powerful command sequences.

Advanced Loop Control in PowerShell

Advanced loop control mechanisms can significantly enhance your scripts’ flexibility and efficiency. PowerShell provides two primary statements for controlling loop execution: break and continue. These statements offer fine-grained control over loop iterations, allowing scripts to respond dynamically to various conditions.

Using the Break Statement

The break statement immediately terminates a loop, regardless of its initial condition. This can be particularly useful when searching for a specific item in a collection or when an operation meets a critical error that requires aborting the loop. Here’s how it can be used:

foreach ($number in 1..100) {
    if ($number -eq 50) {
        Write-Host "Number 50 found, stopping loop."
        break
    }
}

In this example, the loop iterates through numbers 1 to 100, but terminates as soon as it reaches the number 50. The break statement is invaluable for efficiency, ensuring that the loop does not continue processing once its objective is achieved or if proceeding further is unnecessary.

Leveraging the Continue Statement

Conversely, the continue statement skips the remainder of a loop’s current iteration, moving directly to the next iteration. This is useful for bypassing specific items in a collection without exiting the loop entirely. Consider a scenario where you need to process files but skip those that are hidden:

Get-ChildItem | ForEach-Object {
    if ($_.Attributes -match 'Hidden') {
        Write-Host "Skipping hidden file: $($_.Name)"
        continue
    }
    # Process non-hidden files
}

This script processes files in the current directory, skipping over and indicating hidden files while proceeding with others. The continue statement enables selective iteration, focusing processing power on relevant items.

Practical Applications and Considerations

When incorporating break and continue into your scripts, it’s important to consider their impact on readability and logic flow. These statements can significantly alter a loop’s behavior, so judicious use ensures your scripts remain clear and maintainable.

  • Use break for efficiency: Stop loops as soon as they’ve achieved their purpose, especially in large datasets.
  • Employ continue for precision: Skip over elements that don’t require processing, streamlining your operations.

Understanding and utilizing these advanced loop control techniques allows for the creation of more nuanced and efficient PowerShell scripts. Whether you’re managing large collections of data or needing precise control over script execution, these tools are indispensable for sophisticated script development.

Best Practices and Performance Considerations for PowerShell Loops

As we delve into refining our PowerShell scripting skills, it’s crucial to highlight some best practices and performance considerations when working with loops. These insights aim to enhance both the efficiency of your scripts and their readability, ensuring they not only perform well but are also maintainable and understandable.

Write Readable Loops

  • Keep it Simple: Complexity in loops can lead to errors and difficulties in maintenance. Aim for simplicity, ensuring your loops are easy to understand at a glance.
  • Descriptive Variable Names: Use clear and descriptive variable names. For instance, $server is more informative than $s, making your code more readable.

Optimize Performance

  • Limit Scope of Variables: Define variables in the smallest scope necessary. Variables declared outside a loop can be modified inside the loop but can lead to unintended consequences and memory bloat.
  • Avoid Unnecessary Computations: Inside loops, especially those with a significant number of iterations, avoid unnecessary computations. For example, calculate values that remain constant outside the loop.

Use the Right Loop for the Task

  • Choosing For vs. ForEach: Use for loops when you need explicit control over the loop’s indexing or when working with numeric ranges. ForEach is more suited for iterating directly over collections where the index is not needed.
  • Pipeline Efficiency with ForEach-Object: When working with large datasets or when memory management is a concern, consider using ForEach-Object in pipelines. It processes items one at a time, reducing memory usage.

Handling Large Collections

  • Consider Pipeline Processing: PowerShell’s pipeline can handle large collections efficiently by processing items one at a time. This approach is particularly useful when working with data-intensive commands.
  • Selective Processing: Use Where-Object to filter items before processing them with ForEach-Object, reducing the number of iterations and focusing on relevant data.

Debugging Loops

  • Incremental Testing: Test loops with a smaller subset of data before running them on the full set. This approach helps in identifying logic errors or performance issues early.
  • Use Write-Verbose for Debugging: Incorporate Write-Verbose statements within your loop to output debugging information without cluttering your script’s main output.

Wrapping Up on PowerShell Loops

So, we’ve walked through the essentials of PowerShell loops together. It’s clear these loops are more than just code; they’re your toolkit for automating tasks, big or small, in the world of PowerShell scripting. From simple for loops to ForEach and ForEach-Object, we’ve covered the ground you’ll need to stand on to make your scripting tasks a breeze.

Loops are about making life easier, whether you’re automating server checks, managing files, or just making your daily tasks a bit more manageable. It’s all about doing more with less—less time, less manual effort, and less room for error.

Your Next Steps in PowerShell

There’s a lot more to PowerShell than loops, of course. What’s your next challenge? Maybe you’re looking to dive deeper into error handling, explore advanced functions, or start building your own modules. Whatever it is, there’s always another level to unlock.

For those who are keen to dive deeper, consider checking out Server Academy. It’s a great resource for expanding your PowerShell knowledge, with courses ranging from the basics to more advanced topics.

Share Your Thoughts and Experiences

Have you run into interesting scenarios with PowerShell loops? Or maybe you’ve got questions or tips you’d like to share? Dropping a comment below isn’t just about sharing your own story; it’s about contributing to a community where everyone, from beginners to seasoned pros, can learn something new.

Let’s keep the conversation going. Sharing knowledge is how we all grow, and who knows, your insight might just be the solution someone else has been searching for.

One of the most fundamental functions in programming besides “If, Else” are loops. They allow you to process data or run a function until a certain condition is reached. In PowerShell, we can use different types of loops For loop, ForEach, While, Do While, and Do Until.

Knowing when to use what is important to write better Powershell scripts. Especially the difference between the three while loops is sometimes hard to understand.

In this article

In this article, we are going to take a look at the different loop functions that we can use in PowerShell, how to use them, and what the differences are between them.

The For Loop in PowerShell is pretty much the most basic loop that you can use. It iterates a specified number of times through a part of the script until the condition is met.

To use the For loop in PowerShell you will need to specify a counter $i, the condition $i -lt 5 (run as long as $i is less than 5) and increase the counter.

For ($i = 0; $i -lt 5; $i++) {
    Write-host $i 
}

Increasing the counter can also be done inside the script. This allows you to only increase the counter when a specific condition is met in your script.

For ($i = 0; $i -lt 5) {
    Write-Host $i;    
    $i++
}

You can also iterate over an array with a simple For Loop in PowerShell. We can take the array length as part of the condition and iterate through the array until we have processed all the items in the array.

It’s easier to use a foreach loop to process an array than a for loop, more about that later.

$fruit = @('apple','pear','banana','lemon','lime','mango')

# -le means less or equal to
For ($i = 0; $i -le $fruit.length; $i++) {
    Write-Host $fruit[$i];    
}

PowerShell Foreach 1..10

PowerShell also has a shorthand that you can use for a loop. You can define a range, for example, 1..10 and then loop through each number in the range with a ForEach statement. This allows you to specify how many times you want to run the script and just pipe the script behind it.

$path = "C:\temp"

# Create a new file ForEach 1..10 number 
1..10 | % {
    $newFile = "$path\test_file_" + $_ + ".txt";
    New-Item $newFile
}

PowerShell Foreach and ForEach-Object Loop

To process each item in an array or collection you can use the ForEach functions in PowerShell.

There are two types of foreach functions in PowerShell, we have foreach and ForEach-Object. The difference between the two is that foreach will load the entire collection in the memory before it starts processing the data, which ForEach-Object will process the data one at a time. This makes ForEach-Object perfect to pipe behind another function.

ForEach-Object has two shorthands that you can use, ForEach and %. The place where you use ForEach determines which version of the two is used.

$fruits = @('apple','pear','banana','lemon','lime','mango')

# Foreach - Loads all the fruits in the memory and process it
# Takes 21,4553 miliseconds
Foreach ($fruit in $fruits) {
    Write-Host $fruit;
}

#Shorthand for foreach
# Takes 14,3926 miliseconds
$fruits.foreach( {
    Write-Host $_;
}) 

# ForEach-Object 
# Takes 7,8812 miliseconds
$fruits | ForEach-Object {Write-Host $_}

# Shorthand for ForEach-Object
# Takes 7.3507 miliseconds
$fruits | ForEach {Write-Host $_}

# Also a Shorthand for ForEach-Object
# Takes 7,2982 miliseconds
$fruits | % {Write-Host $_}

As you can see is foreach a bit slower in this example, but the reason for this is it takes a little bit to load the collection into the memory.

If we take a large data set, with 300.000 records for example, then we can see that foreach can be a lot faster than ForEach-Object. Only the memory consumption would be a bit higher of foreach.

$items = 0..300000

# Takes 180 ms to complete
(Measure-Command { foreach ($i in $items) { $i } }).TotalMilliseconds

# Takes 1300 ms to complete
(Measure-Command { $items | ForEach-Object { $_ } }).TotalMilliseconds

# Takes 850 ms to complete
(Measure-Command { $items.ForEach({ $i })}).TotalMilliseconds

When you use which function really depends on your dataset. If you need to process a lot of data, then ForEach-Object would be the best choice to avoid memory problems. Small data sets can perfectly be processed with ForEach.

Another advantage of ForEach-Object is that you can pipe another cmdlet behind it, like exporting it to CSV for example.

ForEach-Object Script Blocks

ForEach-Object allows you to use script blocks which can be really useful when you need to log the process or clean up when the script is completed.

$path = "C:\temp"
$totalSize = 0

Get-ChildItem $path | ForEach-Object -Begin {
        Write-Host "Processing folder $path"
    } -Process {
        $totalSize += ($_.length / 1kb)
    } -End {
        Write-host $totalSize "Kb"
    }

Powershell Do While Loop

The PowerShell Do While loop is used to run a script as long as the condition is True or met. You also have the While loop in PowerShell, without the Do part. They are basically the same, both run until a condition is met.

If you run the scripts below, you will see that they both great 10 test files in the temp folder. Both run as long as $i is less than 10.

$i = 0;
$path = "C:\temp"

# Do While loop
Do {
    # Do Something
    $newFile = "$path\dowhile_test_file_" + $i + ".txt";
    New-Item $newFile
    $i++;
}
While ($i -lt 10)

# While loop
$i = 0;
While ($i -lt 10) {
    # Do Something
    $newFile = "$path\while_test_file_" + $i + ".txt";
    New-Item $newFile
    $i++;
}

But there is one big difference between the two. Do While will always run one time atleast, no matter the condition that you are using. The while loop will only run when the condition is met.

Take the following example, we want to run the script, as long $i is less than 10. But we have set the counter to 15 to start with. As you will see when you run the script is that the Do While does run one time, and the while does not run at all.

$i = 15;

Do {
    Write-host "Do While $i is less then 15";
    $i++;
}
While ($i -lt 10)

$i = 15;
while ($i -lt 10)
{
    Write-host "While $i is less then 15";
    $i++;
}

You often use a do-while loop in PowerShell when you are waiting for a condition to be met, for example until a process is finished or as in the example below, until the internet connection is offline.

PowerShell won’t continue to the Write-Host line until the while condition is met. So in this example, we are testing the internet connection with Test-Connection. It will return true when we have a connection, and otherwise, it will return false.

Do {
    Write-Host "Online"
    Start-Sleep 5
}
While (Test-Connection -ComputerName 8.8.8.8 -Quiet -Count 1)

Write-Host "Offline"

Creating a Sleep Loop in PowerShell

If you want to create a loop that checks if a service is back online, or for a file to be created then the best option is to use a sleep inside your loop.

Without the sleep part, the script will run as fast as possible which can be a couple of 1000 iterations per second or more.

With the Start-Sleep cmdlet, we can initiate a little break before the next iteration:

Do {
    Write-Host "Online"
    Start-Sleep 5
}
While (Test-Connection -ComputerName 8.8.8.8 -Quiet -Count 1)

Write-Host "Offline"

In the example above we wait 5 seconds before we test the connection to 8.8.8.8 again. You can also use milliseconds instead of seconds the start-sleep command.

Start-Sleep -Miliseconds 50

PowerShell Do Until Loop

Do Until is pretty much the same as Do While in PowerShell. The only difference is the condition in which they run.

  • Do While keeps running as long as the condition is true. When the condition is false it will stop.
  • Do Until keeps running as long as the condition is false. When the condition becomes true it will stop.
Do {
    Write-Host "Computer offline"
    Start-Sleep 5
}
Until (Test-Connection -ComputerName 'lab01-srv' -Quiet -Count 1)

Write-Host "Computer online"

When to use While or Until really depends on what you want to do. Is basis you can say that when the exit condition must be true, then use Until. If the exit condition is negative (false) then you should use While.

Stopping a Do While/Until loop

In PowerShell, we can use Break to stop a loop early. It’s best to limit the use of breaks in your loops because they make your code harder to read. If you have structured your code well, then you really don’t need it.

$i=0;
Do {
    Write-Host "Computer offline"
    Start-Sleep 1
    $i++;

    if ($i -eq 2) {
        Break
    }
}
Until (Test-Connection -ComputerName 'test' -Quiet -Count 1)

Using Continue in a PowerShell Loop

Another useful method that you can use inside a do-while/until loop in PowerShell is Continue. With Continue you can stop the script inside the Do body and continue to the next iteration of the loop.

This can be useful if you have a large script inside a Do block and want to skip to the next item when a certain condition is met.

$servers = @('srv-lab01','srv-lab02','srv-lab03')

Foreach ($server in $servers) {
    
    if ((Test-Connection -ComputerName $server -Quiet -Count 1) -eq $false) {
        Write-warning "server $server offline"
        Continue
    }

    # Do stuff when server is online
}

PowerShell Loop Examples

Below you will find a couple of loop examples that may help to create your own loops.

PowerShell Infinite Loop

You can create an infinite loop in PowerShell with the While loop function. While will keep running as long as the condition is true. So to create an infinite loop we can simply do the following:

While ($true) {
    # Do stuff forever
    Write-Host 'looping'

    # Use Break to exit the loop
    If ($condition -eq $true) {
        Break
    }
}

To exit the infinite loop you can use either Ctrl + C or based on a condition with Break.

Powershell Loop Through Files

To loop through files we are going to use the foreach-object function. Files are objects that we can get with the get-childitem cmdlet, so we can pipe the foreach-object behind it. Another reason to use ForEach-Object instead of foreach is that we don’t know upfront how many files we are going to process.

Foreach will load all the data in the memory, which we don’t want with an unknown data set.

$path = "C:\temp"
$csvItems = 0

Get-ChildItem $path | ForEach-Object {
    $_.Name;

    If ($_.Extension -eq '.csv') {
        $csvItems++;
    }
}

Write-host "Total CSV Files are $csvItems";

If you want to include the subfolder as well you can use the -recurse option. Use -filter to get only the .csv files for example.

Get-ChildItem $path -recurse -filter *.csv

Loop through a text file

In PowerShell, you can loop through a text file line for line. This can be really useful if you want to automatically read out log files for example.

The example below works fine for small files, but the problem is that Get-Content will read the entire file into the memory.

$lineNr = 0

foreach($line in Get-Content c:\temp\import-log.txt) {
    if($line -match 'warning'){
        # Work here
        Write-warning "Warning found on line $lineNr :"
        Write-warning $line
    }

    $lineNr++;
}

To read and process larger files with PowerShell you can also use the .Net file reader:

foreach($line in [System.IO.File]::ReadLines("c:\temp\import-log.txt"))
{
       $line
}

Wrapping Up

I hope the example helped with creating your PowerShell For, Foreach-Object, Do While, and Until loops. If you have any questions just drop a comment below.

A loop is a sequence of instruction(s) that is continually repeated until a certain condition is reached. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming. A loop lets you write a very simple statement to produce a significantly greater result simply by repetition. If the condition has been reached, the next instruction «falls through» to the next sequential instruction or branches outside the loop.

# Foreach

ForEach has two different meanings in PowerShell. One is a keyword (opens new window) and the other is an alias for the ForEach-Object (opens new window) cmdlet. The former is described here.

This example demonstrates printing all items in an array to the console host:

This example demonstrates capturing the output of a ForEach loop:

Like the last example, this example, instead, demonstrates creating an array prior to storing the loop:

# For

A typical use of the for loop is to operate on a subset of the values in an array.
In most cases, if you want to iterate all values in an array, consider using a foreach statement.

# ForEach() Method

Instead of the ForEach-Object cmdlet, the here is also the possibility to use a ForEach method directly on object arrays like so

or — if desired — the parentheses around the script block can be omitted

Both will result in the output below

# ForEach-Object

The ForEach-Object cmdlet works similarly to the foreach (opens new window) statement, but takes its input from the pipeline.

# Basic usage

Example:

Foreach-Object has two default aliases, foreach and % (shorthand syntax). Most common is % because foreach can be confused with the foreach statement (opens new window). Examples:

# Advanced usage

Foreach-Object stands out from the alternative foreach solutions because it’s a cmdlet which means it’s designed to use the pipeline. Because of this, it has support for three scriptblocks just like a cmdlet or advanced function:

  • Begin: Executed once before looping through the items that arrive from the pipeline. Usually used to create functions for use in the loop, creating variables, opening connections (database, web +) etc.
  • Process: Executed once per item arrived from the pipeline. «Normal» foreach codeblock. This is the default used in the examples above when the parameter isn’t specified.
  • End: Executed once after processing all items. Usually used to close connections, generate a report etc.

Example:

# Continue

The Continue operator works in For, ForEach, While and Do loops. It skips the current iteration of the loop, jumping to the top of the innermost loop.

The above will output 1 to 20 to the console but miss out the number 7.

Note: When using a pipeline loop you should use return instead of Continue.

# Break

The break operator will exit a program loop immediately. It can be used in For, ForEach, While and Do loops or in a Switch Statement.

The above will count to 15 but stop as soon as 7 is reached.

Note: When using a pipeline loop, break will behave as continue. To simulate break in the pipeline loop you need to incorporate some additional logic, cmdlet, etc. It is easier to stick with non-pipeline loops if you need to use break.

Break Labels

Break can also call a label that was placed in front of the instantiation of a loop:

Note: This code will increment $i to 8 and $j to 13 which will cause $k to equal 104. Since $k exceed 100, the code will then break out of both loops.

# While

A while loop will evaluate a condition and if true will perform an action. As long as the condition evaluates to true the action will continue to be performed.

The following example creates a loop that will count down from 10 to 0

Unlike the Do-While loop the condition is evaluated prior to the action’s first execution. The action will not be performed if the initial condition evaluates to false.

Note: When evaluating the condition, PowerShell will treat the existence of a return object as true. This can be used in several ways but below is an example to monitor for a process. This example will spawn a notepad process and then sleep the current shell as long as that process is running. When you manually close the notepad instance the while condition will fail and the loop will break.

# Do

Do-loops are useful when you always want to run a codeblock at least once. A Do-loop will evaluate the condition after executing the codeblock, unlike a while-loop which does it before executing the codeblock.

You can use do-loops in two ways:

  • Loop **while** the condition is true:
  • Loop **until** the condition is true, in other words, loop while the condition is false:
  • Real Examples:

    Do-While and Do-Until are antonymous loops. If the code inside the same, the condition will be reversed. The example above illustrates this behaviour.

    # Syntax

  • for ( ; ; ) { }
  • | Foreach-Object { }
  • foreach ( in ) { }
  • while ( ){ }
  • do { } while ( )
  • do { } until ( )
  • .foreach( { } )
  • # Foreach

    There are multiple ways to run a foreach-loop in PowerShell and they all bring their own advantages and disadvantages:

    Solution Advantages Disadvantages
    Foreach statement Fastest. Works best with static collections (stored in a variable). No pipeline input or output
    ForEach() Method Same scriptblock syntax as Foreach-Object, but faster. Works best with static collections (stored in a variable). Supports pipeline output. No support for pipeline input. Requires PowerShell 4.0 or greater
    Foreach-Object (cmdlet) Supports pipeline input and output. Supports begin and end-scriptblocks for initialization and closing of connections etc. Most flexible solution. Slowest

    # Performance

    While Foreach-Object is the slowest, it’s pipeline-support might be useful as it lets you process items as they arrive (while reading a file, receiving data etc.). This can be very useful when working with big data and low memory as you don’t need to load all the data to memory before processing.

    Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии
  • История сбоев windows 10
  • Не могу попасть на рабочий стол windows 10
  • Как открыть устранение неполадок windows 10 при загрузке компьютера
  • Описание dll библиотек windows
  • Autodesk inventor для windows 7