Getty Images/iStockphoto

Manage Learn to apply best practices and optimize your operations.

PowerShell looping examples for the 4 key commands

There are many instances where looping is a valuable tool in your PowerShell script. Knowing how to use them will serve you well. Evaluate these four loop commands.

Looping in PowerShell enables IT admins to repeat tasks automatically without repeating code. With several looping options, you can choose to either loop through each item of an array or to loop until a certain condition is met.

PowerShell is an automation tool and scripting language that admins can use to configure systems and automate administrative tasks. Looping helps ensure consistent results.

Let's take a brief look at the four main types of loops in PowerShell:

  1. foreach
  2. Foreach-Object
  3. While
  4. Do-While

Foreach

A foreach loop enables admins to iterate through an array and specify the variable name for each item. Here's an example that returns all subdirectories and lists the files in that directory:

$directories = Get-ChildItem -Directory
foreach ($directory in $directories) {
    Get-ChildItem $directory -File
}

After foreach, include the variable that you want to use to reference each item in the array, followed by in and then the array itself. Best practice guidance is to use a singular noun for the variable and a plural noun for the array. This grammatical convention makes code easier to read and understand.

Foreach-Object

A Foreach-Object loop accomplishes the same thing as a foreach loop, but uses the pipeline to do it. The same example as before would instead look like:

Get-ChildItem -Directory | ForEach-Object {Get-ChildItem $_ -File}

Rather than use $directory to reference the item in each iteration, use the built-in $_ variable. However, you can also use $PSItem instead of $_.

If you are running commands interactively, Foreach-Object is usually easier to use -- especially while using the % alias. But in scripts, a foreach loop is more explicit, which enables foreach loop nesting.

While

The PowerShell loop while runs a block of code while a conditional statement returns true. For example, part of an onboarding script adds a license to an Azure Active Directory user that enables an Exchange online mailbox. If the script must complete additional tasks on the mailbox, it will have to wait until the mailbox has provisioned. This could look something like:

$upn = '[email protected]'
while (-not ($mbx = Get-EXOMailbox $upn -ErrorAction SilentlyContinue)) {
    Start-Sleep -Seconds 60
}
# do things to $mbx

If the $upn mailbox does not exist, it will return an error and the -not parameter will evaluate the statement to true and the loop will proceed.

Note that the conditional statement is evaluated before the code within the while loop runs. If it evaluates to false, the while loop will not run.

Do-While

A do-while loop is similar to a while loop, but the code inside of the do loop will always run at least once. After it runs, it evaluates the conditional statement -- while -- to see if it should exit the do loop.

Using the same example as our while loop above, we switch it around to look like this:

$upn = '[email protected]'
do {
    Start-Sleep -Seconds 60
} while (-not ($mbx = Get-EXOMailbox $upn -ErrorAction SilentlyContinue))
# do things to $mbx

This code results in the same end goal: PowerShell waits until the mailbox is provisioned before proceeding. However, it sleeps for 60 seconds before checking to see if the mailbox exists.

Dig Deeper on Scripting, Scheduling and IT Orchestration

SearchSoftwareQuality
SearchAppArchitecture
SearchCloudComputing
SearchAWS
TheServerSide.com
SearchDataCenter
SearchServerVirtualization
Close