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.
In this PowerShell guide, we explain how to use the For loop, the ForEach-Object loop, and the While, Do-While and Do-Until loops.
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.
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.”
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.
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. 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.
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.
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]
}
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
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
}
}
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. |
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.
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.