/
/

How to Execute a PowerShell Loop: Guide to Boosting Your Scripting Efficiency

by Lauren Ballejos, IT Editorial Expert
reviewed by Stan Hunter, Technical Marketing Engineer
guide to PowerShell loops blog banner image

Key Points

  • How to execute a PowerShell loop
      • for: Repeat a command a set number of times
        • for ($i = 0; $i -lt 10; $i++) { # code }
    • foreach: Iterate over each item in a collection
      • foreach ($item in $collection) { # code }
    • while: Continue as long as a condition is true
      • while ($condition) { # code }
    • do while: Always run at least once, then continue if condition is true
      • do { # code } while ($condition)
    • do until: Always run at least once, then continue until condition is true
      • do { # code } until ($condition)
  • How to repeat a command
    • Use a for loop with an increment
      • Example: repeat 5 times
        • for ($i = 0; $i -lt 5; $i++) { # command }

PowerShell is a powerful scripting language that allows you to automate tasks on your computer. System administrators and IT professionals can use PowerShell to boost IT efficiency and productivity by executing commands through the tool’s command-line interface. It also allows IT technicians to loop through a set of instructions multiple times, enhancing scripting efficiency in your workflows.

In this article, we’ll answer the question, “How do I run a loop in PowerShell?” by guiding you through each type of PowerShell loop and providing examples of how to use them effectively.

💡 If videos are your thing, check out How to Execute a PowerShell Loop.

Get practical advice and walkthroughs of fundamental scripting with Powershell

Watch the webinar here

Types of PowerShell loops (for loop, foreach loop, while loop, do while loop, do until loop)

To understand how to loop in PowerShell, let’s start by understanding the types of loops. Each PowerShell loop variation has its own unique syntax and usage. Understanding the differences between them will let you choose the most appropriate one for your needs.

Syntax and usage of the for loop in PowerShell

The for loop is a classic counter-controlled loop construct in programming languages such as PowerShell. It’s typically used when you need to run a block of code a known number of times, or when you need to track an item’s position in a collection. It consists of three parts: the initialization, the condition, and the iteration:

  • The initialization sets the initial value of a variable.
  • The condition checks if the loop should continue (e.g., by checking if the variable is less than or greater than a specific number).
  • The iteration updates the variable after each iteration.

To use the for PowerShell loop, follow this syntax:

for ($i = 0; $i -lt 10; $i++) { # Your code here }

In this example, the loop will execute 10 times, starting from zero and incrementing by one in each iteration.

TIP: If you simply need to iterate over every item in an array or collection, Microsoft recommends using a foreach statement instead. We’ll be discussing that loop in the next section.

Syntax and usage of the foreach loop in PowerShell

The foreach loop in PowerShell is used to iterate over a collection of items, such as an array or a list. It automatically assigns each item to a variable, allowing you to perform actions on each individual item.

To use the foreach PowerShell loop, follow this syntax:

foreach ($item in $collection) { # Your code here }

In this example, the loop will iterate over each item in the $collection variable, and you can access each item using the $item variable within the loop.

NOTE: PowerShell has both a foreach loop and ForEach-Object cmdlet. The former loads the entire collection into memory before processing, which is fast for in-memory arrays but can be memory-intensive for very large datasets. The cmdlet, on the other hand, accepts pipeline input and processes one item at a time which makes it ideal for streaming large data sets.

Syntax and usage of the while loop in PowerShell

The while loop in PowerShell is used when you want to repeat a set of instructions as long as a certain condition is true. It checks the condition before each iteration and exits the loop when the condition becomes false.

To use the while PowerShell loop, follow this syntax:

while ($condition) { # Your code here }

In this example, the loop will continue executing as long as the $condition is true.

Syntax and usage of the do while loop in PowerShell

The do until is a post-test loop that runs its statement block first, then evaluates the condition. It continues executing until the condition becomes true, which is the opposite of the do while loop. It executes a set of instructions until a certain condition becomes true. This means that the loop will always execute at least once, even if the condition is initially true.

To use the do while PowerShell loop, follow this syntax:

do { # Your code here } while ($condition)

In this example, the loop will execute the code block at least once, and then continue executing as long as the $condition is true.

Syntax and usage of the do until loop in PowerShell

The do until loop in PowerShell is the opposite of the do while loop. It executes a set of instructions until a certain condition becomes true. This means that the loop will always execute at least once, even if the condition is initially true.

To use the do until PowerShell loop, follow this syntax:

do { # Your code here } until ($condition)

In this example, the loop will execute the code block at least once, and then continue executing until the $condition becomes true.

How do I repeat a PowerShell command?

Now that you understand the basics of how to loop in PowerShell, let’s take it a step further. One of the easiest ways to repeat a PowerShell command is by simply using a loop construct and specifying the number of times you want the command to be executed.

For example, if you want to repeat a command 5 times, you can use a for loop like this:

for ($i = 0; $i -lt 5; $i++) { # Your command here }

This will execute the command five times: the $i variable will be incremented by one after each iteration, and the loop will stop once the variable’s value reaches five.

Examples of PowerShell loops

Below are a few basic examples of how you can use loops in PowerShell to automate tasks and improve your scripting efficiency.

Example 1: Printing numbers from 1 to 10 using a for loop

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

This will print the numbers from 1 to 10 in the PowerShell console.

Example 2: Iterating over an array using a foreach loop

$fruits = @(“apple”, “banana”, “orange”)

foreach ($fruit in $fruits) { Write-Output $fruit }

This will iterate over each item in the $fruits array and print it in the PowerShell console.

Other ways to automate using PowerShell

In addition to loops, PowerShell offers many other ways to automate tasks and improve your scripting efficiency. Here are a few examples:

  1. Functions: You can define reusable functions in PowerShell to encapsulate a set of instructions and use them whenever needed.
  2. Modules: PowerShell modules allow you to package and share your scripts, making it easy to reuse code across different projects.
  3. Pipelines: PowerShell pipelines enable you to chain commands together, passing the output of one command as the input to another, which can greatly simplify complex tasks.
  4. Scheduled tasks: You can use PowerShell to create scheduled tasks that automate the execution of scripts at specific times or intervals.

Get started with out-of-the-box Powershell scripts that can reduce manual workloads.

Browse the NinjaOne Script Hub library.

Boost scripting efficiency with PowerShell loops

Knowing how to loop in PowerShell will give you major productivity gains, enhancing your scripting efficiency. By understanding the syntax and usage of each loop type, you can choose the most appropriate one for your specific scenario. Incorporating these techniques into your PowerShell scripting workflow will save untold hours of your IT department’s time and effort.

Learning how to loop in PowerShell is just one technique for automating repetitive tasks with PowerShell. If you need more ideas for boosting productivity and efficiency, check out our guide on automating Office 365 installation with PowerShell or our list of the top 10 repetitive helpdesk tasks to automate.

FAQs

The for and foreach statements are the fastest PowerShell loops for in-memory collections, since they avoid the overhead of the PowerShell pipeline.

Use a loop when you need to repeat the same action across a set of items or until a condition is met. A good example is applying a setting to every user in a list, or checking a service repeatedly until it starts.

For more complex automation, other PowerShell features may be a better fit: functions are best when you want to reuse the same block of logic in different places, pipelines work well when you’re transforming data step by step, and scheduled tasks are the right choice when you need a script to run automatically at set times.

Loops, functions, pipelines, and scheduled tasks often work best together rather than as alternatives.

You might also like

Ready to simplify the hardest parts of IT?