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.
{
<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.
The shebang would look something like this.
Mark the PowerShell script file as an executable.
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.
Now, implement the foreach loop to work with each element of the array.
{
echo $city
}
Test the code by running the script.
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.
Now, implement the foreach loop to print the numbers one by one.
{
echo $number
}
Let’s put the code into action.
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.
{
echo $file
}
Run the code.
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.
{
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.
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.
Now, we can call the method and describe a simple echo command per iteration.
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 |
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!