business.com receives compensation from some of the companies listed on this page. Advertising Disclosure
Home

PowerShell Basics: Programming With Loops

Tim Ferrell
business.com Contributing Writer
Updated Nov 22, 2022

We show you how to use the For loop, ForEach-Object loop, and the While and Do-While loops.

PowerShell is a great tool to use for programmers and nonprogrammers alike. Being able to automate both simple and complex scripts is an invaluable asset to businesses, daily tasks and even recreational use. One of the more difficult tasks of attempting automation is writing loops for your scripts. Loops are essential in being able to automate mundane tasks that take up too much of your valuable time. In this PowerShell tutorial, we will show you how to use the For loop, ForEach-Object loop, and the While, Do-While and Do-Until loops. 

What is PowerShell?

PowerShell is an open-source scripting language that helps tech pros who may not necessarily be familiar with software programming to design efficient scripts and tools to assist in their daily work tasks. PowerShell was originally designed with “easy to understand” in mind. 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 anything and everything one might need. 

In 2002, Jeffrey Snover, working for Microsoft at the time, knew that the command-line interface for Windows was not as capable as Linux, Microsoft’s competitor. To solve this, he created a document outlining his plans for a program that could keep up with and possibly succeed the old command lines; thus, PowerShell was born. The program was such a success during the three-year implementation at Windows that as of Windows 7, PowerShell became the default install on all Windows platforms. [Read related article: How to Install Windows Patches With PowerShell for Free]

Did you know?Did you know? Since 2016, PowerShell has been available on MacOS, Linux and other *nix operating systems.

Much like other shells, PowerShell has binary commands to execute most actions. For example, you can run commands to read files, ping computers and even 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 dash in the middle and a noun at the end. The verbs describe what action the cmdlet is going to perform. “Copy-Item” copies a file, and “Get-Content” gets text from a file

Not sure what verb you’re looking for? Try “Get-Verb” for a list of accepted verbs. While there aren’t any approved nouns in PowerShell, you can still get a list of available objects that are counted as nouns by filtering through the “Get-Command” function. [Read related article: Understanding Functions in PowerShell]

TipTip: Need to know exactly which verbs are accepted? Try using “Get-Verb” for a list of acceptable syntaxes.

Programming with loops

PowerShell loops, at their most basic, simply repeat the same set of commands a set number of times. Ideal for performing consistent actions for a set period of time or a certain number of records, loops can simplify your scripts in a big way. PowerShell in particular features a number of cmdlets – notably those that begin with the verb Get – that return objects containing large numbers of similar data.

There are several types of loops available in PowerShell, and in many cases, more than one loop technique can be used effectively. At times, determining the most efficient loop type is required, either from a performance or code readability perspective.

ForEach-Object loop

PowerShell screenshot

In many cases using the ForEach-Object cmdlet is the best way to loop through an object. At its most simple, 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:

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

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

Get-WMIObject Win32_LogicalDisk | % FreeSpace

PowerShell For loop

PowerShell screenshot

For loops are typically used to iterate through a set of commands a specified number of times, either to step through an array or object, or just to repeat the same block of code as needed. A For loop is constructed by setting the value of a variable when entering the loop, 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)
               }

For loops can be used 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]
               }

While, Do-While and Do-Until loops

PowerShell screenshot

The third type of loop that 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. While and Do-While loops are both used to perform an 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.

Do-While and Do-Until loops both begin with the Do keyword prefacing a script block, 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)

While loops perform identically to Do-While loops, only 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 – 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.

Bottom LineBottom Line: Make sure you understand which loop type is necessary for your script building: For, While, Do-While or Do-Until.

In some situations, you may need to exit a loop early based on something other than the loop’s condition. In this case, the Break keyword can be invoked in order 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
               }
    }

Sean Peek contributed to the writing and reporting of this article. 

Image Credit: scyther5/Getty
Tim Ferrell
business.com Contributing Writer