Post navigation

PowerShell Tutorial – Loops (For, ForEach, While, Do-While, Do-Until)

Loops are an essential construct in any programming language as they enable a block of code to be repeatedly executed. This can be useful for iterating through items in an object or repeatedly performing an operation.

This tutorial covers the five types of loops that are provided in PowerShell – namely For, ForEach, While, Do-While, and Do-Until.

ForEach Loop

The foreach statement is very useful in PowerShell when you need to loop through an array or loop through items in an object.

ForEach allows the loop to evaluate the number a certain type of objects in an array or parent object and loop through those objects. One thing to bear in mind is that a ForEach loop is that there is a performance penalty for this convenience.

The below example, shows a ForEach Loop operating on a object, the code assigns the object resulting from the Get-process cmdlet to a variable, and then iterates through the process items in the object and displays the process name.