fbpx

How To Use PowerShell Foreach Loop

The concept of a loop is present in almost all programming languages, and PowerShell is no exception. The PowerShell foreach loop is one of the most widely used loop structures in PowerShell. A foreach loop scans the full collection of items and executes some form of code for every single one of them.

You will discover how each kind of foreach loop functions in this post, along with when to employ it instead of another. You will be proficient in all of the different foreach loop types.

What Is Powershell Foreach Loop? 

There are various ways to process a group of things using PowerShell. A collection could be retrieved from files. The collection might also come about as a result of a command run or a Where-Object cmdlet-filtered result.

The Foreach statement, which can be used as a loop, a cmdlet, or a function, will be utilized when you need to take some action against the individuals in this collection. Generally speaking, loops in PowerShell let you keep repeating a command or set of commands up until a condition is satisfied.

The processes will recur if a Foreach loop is used, processing each item in the collection one at a time. As a result, the code is smaller and easier to read.

Five different loop types are available in PowerShell: foreach, for, do/while, do/until, and while.

Powershell Foreach keyword Basics With Syntax

The foreach type of loop is one of the most popular loop types in PowerShell. A foreach loop iterates through a list of items and ends when it has completed reading the last one. An array or hashtable is frequently used to represent a collection of read items.

Syntax

A PowerShell foreach loop begins with the keyword, then two variables are enclosed in parenthesis. One is for the collection, and the other is for the thing that is being processed right now. Before beginning each iteration of the loop until all items have been handled, the item variable is automatically created and given the value of the following item in the array.

foreach ($<item> in $<collection>){<statement list>}

The variable still holds the last processed item once the loop is finished. A script block that executes a command or a group of commands against each item in the collection is the next part of the syntax.

What are the Three Foreach loop Methods?

In PowerShell, there are three distinct forms of foreach loops. Despite the fact that each has a similar application, it’s critical to recognize the distinctions.

1. The Foreach Statement

A statement is the first kind of foreach loop. PowerShell has a built-in term called “foreach” that is neither a cmdlet nor a function. The syntax for the foreach expression is always “foreach ($i in $array)”.

While the $path variable iterates through each element in the array, the “i” variable represents the iterator or the value of each item.

It should be noted that the iterator variable need not be $i. Any name is acceptable for the variable. The following will achieve the same result as repeating the Add-Content reference:

# Create an array of folders

$folders = @('D:\new folder','D:\new folder\A','D:\new folder\B')

# Perform iteration to create the same file in each folder

foreach ($i in $folders) {
    Add-Content -Path "$i\SampleFile.txt" -Value "THIS IS MY FILE"
}
The Foreach Statement
The Foreach Statement

It is well known that utilising the foreach statement instead of the forEach-Object cmdlet will save time.

2. The Foreach() Method

You’ll also look at the PowerShell V4-added foreach() object method, which is another kind of foreach loop. In Windows PowerShell, all arrays have the foreach() method, which may be used to achieve the same task as foreach and ForEach-Object.

Like the others, the foreach() function provides a standard script block parameter that specifies the steps to be taken during each iteration.

The scriptblock parameter of the foreach() method should include the code to run for each iteration. The current iteration’s object is captured using $_, much like with ForEach-Object.

$servers.foreach({Get-Content -Path "\\$_\c$\App_configuration.txt"})

When processing huge datasets, the foreach() approach is noticeably faster than the other two. Wherever it is possible, I advise using this approach rather than the other two.

$folders = @('D:\new folder','D:\new folder\A','D:\new folder\B')
$folders.ForEach({
    Add-Content -Path "$_\SampleFile.txt" -Value "This is the content of the file"
})
The Foreach() Method

When you want to carry out an operation on each item individually, a foreach loop is fantastic. But let’s say you wish to go a simpler route.

3. The Foreach-Object Cmdlet

ForEach-Object is a cmdlet with parameters that can be used in many different ways, as opposed to foreach, which is a statement that can only be used in one way.

The ForEach-Object cmdlet can traverse across a group of objects, just like the foreach command can. 

The difference this time is that the set of objects and the action to be taken on each one are passed as parameters. Foreach is an alias for the ForEach-Object cmdlet. Depending on how “foreach” is used, either the foreach statement or the forEach-Object is executed.

$folders = @('D:\new folder','D:\new folder\A','D:\new folder\B')
$folders | ForEach-Object (Add-Content -Path "$_\SampleFile.txt" -Value "This is the content of the file")

Seeing whether ($someVariable in $someSet) follows the term “foreach” is a handy approach to distinguish between these scenarios. Otherwise, it’s likely that the code author is employing the alias in any other situation.