In programming, a loop is a simple yet powerful concept. A loop is the repetition of a set of instructions unless a certain condition is met. A proper loop can save time and increase the efficiency of a code. PowerShell, being a scripting language, supports various forms of loops.

In this guide, check out how to use the foreach loop in PowerShell.

PowerShell loops

In principle, all loops are the same. However, for better coding experience and readability, various programming languages implement the loop concept in different ways. In fact, the same language can support multiple types of loops, each with its unique structure.

PowerShell supports several types of loops.

  • for: A standard loop to execute certain tasks a specific number of times.
  • while: It keeps performing a set of operations until the conditions are met.
  • do while: The loop keeps running as long as the condition is true. However, it will always execute the first time.
  • Do-until: It almost works similar to do while. The only difference is, it will only execute if the given condition is not true.
  • foreach-object: This loop performs an operation for each input object.

As the title of the article suggests, we’ll be looking at the foreach loop.

ForEach loop in PowerShell

The code of foreach loop structure is as follows.

ForEach(ITEM in COLLECTION)


{


   


}

Here,

  • ITEM: It’s a single value or object that changes with each iteration.
  • COLLECTION: It can be an array, list of values, collection, or objects.
  • : It’s the block of code that runs once the loop condition is met. It generally uses ITEM.

Foreach is one of the most common and simplest PowerShell loops. It reads an entire collection of items, and for each item, it performs the operation(s) defined.

It can be used for numerous situations, for example, working the contents of a directory.

Foreach loop in practice

In this section, we’ll have a look at some sample implementations of the foreach loop. To execute the codes, I’ve already prepared an empty PowerShell script.

The shebang would look something like this.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-01.png" data-lazy- height="672" src="data:image/svg xml," width="1214">

Mark the PowerShell script file as an executable.

$ chmod x foreach-loop.ps1

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-02.png" data-lazy- height="120" src="data:image/svg xml," width="1216">

Foreach through a string array

In the first demonstration, we’ll be implementing a foreach loop that reads from a string array of city names and prints the city names on the screen.

First, declare the string array.

$cities = ("Tokyo", "New York", "Moscow", "London", "Sydney")

Now, implement the foreach loop to work with each element of the array.

foreach ($city in $cities)


{


    echo $city


}

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-03.png" data-lazy- height="668" src="data:image/svg xml," width="1214">

Test the code by running the script.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-04.png" data-lazy- height="232" src="data:image/svg xml," width="1216">

Foreach through a collection of numbers

In this example, we’ll implement the foreach loop similar to the previous one. The difference is, it will go through an array of numbers instead.

Declare the number array.

$numbers=(9,8,7,6,5,4,3,2,1)

Now, implement the foreach loop to print the numbers one by one.

foreach ($number in $numbers)


{


    echo $number


}

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-05.png" data-lazy- height="670" src="data:image/svg xml," width="1214">

Let’s put the code into action.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-06.png" data-lazy- height="340" src="data:image/svg xml," width="1216">

Foreach through files

It’s one of the most common scenarios to use foreach loops. With the help of other cmdlets, we can get specific info about certain directories/files and use that info to perform necessary actions.

In this example, the foreach loop will check the content of a directory /home/viktor/Desktop/sample_dir and print the name of the files.

foreach($file in Get-ChildItem -Recurse -Path /home/viktor/Desktop/sample_dir)


{


    echo $file


}

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-07.png" data-lazy- height="518" src="data:image/svg xml," width="1216">

Run the code.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-08.png" data-lazy- height="728" src="data:image/svg xml," width="1220">

Here, the cmdlet Get-ChildItem gets the items over the location described. The flag “-Path” describes which directory to look into. If there are multiple levels of sub-directories, then using “-Recurse” will get all the child items recursively. If you want to recurse up to a certain depth, you can also use the “-Depth” parameter. Check out more on Get-ChildItem.

We can also fine-tune the code to search for only specific file extensions.

foreach($file in Get-ChildItem -Recurse -Path /home/viktor/Desktop/sample_dir/*.txt)


{


    echo $file


}

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-09.png" data-lazy- height="464" src="data:image/svg xml," width="1214">

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-10.png" data-lazy- height="604" src="data:image/svg xml," width="1216">

Foreach over CSV

A CSV file is a text database of values, each value separated by a delimiter (comma, mostly). It’s a simple yet effective structure to store structured data in text format. The CSV format is used by various applications and database engines for convenience and ease of use.

We can use the foreach loop to work with individual values of a CSV file and take action accordingly. The following example does just that.

$values = (Get-Content /home/viktor/sample.csv)[0].split(",")


foreach ($value in $values){


    echo $value


}

Foreach method

Up until now, we’ve seen the foreach loop in action, right? In PowerShell, it also appears as the foreach() method. Starting from PowerShell v4, this method exists on arrays or collections of objects. The method has a standard script block as the parameter that contains the actions to take for each iteration.

Let’s have a look at the foreach() method in action. First, create a sample array.

$numbers=(2,4,8,16,32,64,128,256,512)

Now, we can call the method and describe a simple echo command per iteration.

$numbers.ForEach({


    echo $_


})

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-11.png" data-lazy- height="492" src="data:image/svg xml," width="1216">

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-12.png" data-lazy- height="340" src="data:image/svg xml," width="1216">

Foreach-Object

The foreach loop can also directly work with objects. To do so, there’s a dedicated cmdlet named Foreach-Object. It takes an object as input and iterates through its elements.

In the next example, we’ll search through a specific directory for “.txt” files and use Foreach-Object to act based on each element of the search result.

$names = Get-ChildItem -Recurse /home/viktor/Desktop/sample_dir/*.txt


$names |


Foreach-Object {


    echo $_


}

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-13.png" data-lazy- height="490" src="data:image/svg xml," width="1212">

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/PowerShell-Foreach-Loop-14.png" data-lazy- height="596" src="data:image/svg xml," width="1220">

As you can see, the core structure of Foreach-Object is quite similar. The only difference is, you can pass the object using piping.

Final thoughts

The foreach loop in PowerShell is a simple but effective and powerful loop. It can operate based on objects, arrays, or individual elements. This guide demonstrates some of the common implementations of the foreach loop.

Besides the foreach loop, PowerShell supports other standard loops, like the for a loop. Check out this guide for loop in PowerShell.

Happy computing!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/10/echo/profile-photo-1.jpg61759d6756eef.jpg" height="112" src="data:image/svg xml," width="112">

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.