Powershell

PowerShell Foreach Loop

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)
{
    <code>
}

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.
  • <code_block>: 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.

$ nano foreach-loop.ps1

The shebang would look something like this.

$ #!/snap/bin/powershell

Mark the PowerShell script file as an executable.

$ chmod +x foreach-loop.ps1

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
}

Test the code by running the script.

$ ./foreach-loop.ps1

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
}

Let’s put the code into action.

$ ./foreach-loop.ps1

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
}

Run the code.

$ ./foreach-loop.ps1

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
}

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 $_
})

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 $_
}

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

Sidratul Muntaha

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