PowerShell ForEach Loop, ForEach-Object Cmdlet – Beginner’s Guide
PowerShell’s ForEach
loop and ForEach-Object
cmdlets allow you to iterate over a collection of objects and perform a specific action on each item in the collection. In this article, we’ll take a look at how to use these cmdlets to work with collections of objects.
Table of contents
PowerShell ForEach Loop
The ForEach
loop in PowerShell allows you to iterate over a collection of objects, such as an array, a list of files, a set of user accounts, or a list of items. The syntax for the ForEach
cmdlet is as follows:
ForEach (item in collection) {
# code to execute on each item
}
Here is an example of how to use the ForEach loop in PowerShell to iterate over the elements of an array:
$items = 1,2,3,4,5
ForEach ($item in $items)
{
Write-Host "Item: $item"
}
This loop iterates over an array of numbers (The code block inside the loop – the statements between the curly braces) is executed for each iteration of the loop) and prints each number to the console. This will output the following:
Item: 1
Item: 2
Item: 3
Item: 4
Item: 5
You can also use the ForEach loop to iterate over the properties of an object:
#Object
$Employee = [pscustomobject] @{
Name = "Shan Mathew"
Designation = "IT Manager"
Country = "United States"
}
#Get All Properties of the Object
Foreach ($Property in $Employee.PSObject.Properties)
{
Write-Host "$($Property.Name): $($Property.Value)"
}
This will output the following:
Name: Shan Mathew
Designation: IT Manager
Country: United States
You can also use the ForEach
loop to perform actions on each item in a list of objects, such as files or folders. For example:
#Get All Files from a Folder
$Files = Get-ChildItem "C:\Temp" | Where { !$_.PSIsContainer }
#Print Each File Name in the Console
ForEach ($File in $Files) {
Write-host $File.Name
}
In this example, the Get-ChildItem
cmdlet is used to get a list of all the files in the C:\Temp
directory, and the ForEach
loop iterates over the list of files and prints the name of each file to the console.
PowerShell ForEach-Object cmdlet
The ForEach-Object
cmdlet is a cmdlet that allows you to perform an action on each object in a collection of objects. Unlike the ForEach
statement, It uses the pipeline as its input. The syntax for the ForEach-Object
cmdlet is as follows:
<input> | ForEach-Object {
# code to execute on each item
}
Here is an example of using ForEach-Object
to loop over the numbers from 1 to 10:
#Loop between 1 to 10 numbers
1..10 | ForEach-Object {
Write-host $_
}
This prints the numbers between 1 and 10 on the screen. The ForEach-Object is often used in conjunction with the Where-Object
cmdlet to filter the objects in the collection before performing the action. ForEach-Object can be used with any type of object, including arrays, lists, strings, etc. Here are some examples:
- Get a list of all items from a directory –
Get-ChildItem -Path "C:\Temp" | ForEach-Object { $_.Name }
- Get a list of all the processes running on a computer –
Get-Process | ForEach-Object { $_.ProcessName }
- Convert all the strings in a list to uppercase –
"One", "Two", "Three" | ForEach-Object { $_.ToUpper() }
ForEach-Object with -Begin and -End parameters
The -Begin
and -End
parameters allow you to specify script blocks that are executed before and after the iteration through the collection, respectively. For example, let’s iterate through each file in a folder:
Get-ChildItem "C:\Temp" | Where { !$_.PSIsContainer } | ForEach-Object {
Write-Host "Processing file $($_.Name)"
} -Begin {
Write-Host "Start processing files"
} -End {
Write-Host "Finished processing files"
}
In this example, the script block specified with the -Begin
parameter is executed before the iteration starts, and the script block specified with the -End
parameter is executed after the iteration is completed.
You can also use the ForEach
loop to perform actions on each item in a list of objects, such as files or folders. For example:
ForEach Loop Vs. ForEach-Object cmdlet in PowerShell
In PowerShell, the ForEach loop and the ForEach-Object cmdlet are both used to iterate through a collection of objects, but they work slightly differently. When you place ForEach statement at the beginning of the line (E.g., ForEach ($item in $items) {}), it is a traditional loop construct that allows you to execute a block of code for each element in an array or collection.
The ForEach-Object
cmdlet, on the other hand, is a cmdlet that is designed to work with the PowerShell pipeline. It takes input from the pipeline, performs an operation on each object, and passes the results down the pipeline. Here’s an example of using the ForEach-Object
cmdlet: (E.g., Get-ChildItem | ForEach-Object { Write-Host $_.Name }). The ForEach keyword can also be piped to, because it’s also an alias for ForEach-Object. But the reverse is not possible!
Break ForEach Loop and ForEach-Object cmdlet in PowerShell
The break
keyword can be used to exit a ForEach
or ForEach-Object
loop prematurely in PowerShell.
How to Break ForEach Loop in PowerShell?
The ForEach statement allows you to iterate over a collection of items and perform an action on each item. But what if you need to break out of the loop early? To exit a foreach
loop early in PowerShell, you can use the break
keyword. Here’s an example:
$Array = 1..10
Foreach($Val in $Array){
#Stop at 5
if($val -eq 5){
break
}
Write-Host "Value: $val"
}
Output:
Value:Â 1
Value:Â 2
Value:Â 3
Value:Â 4
In the example above, the foreach
loop will iterate through the elements of the $array
array. When the loop reaches the element with a value of 5, the break
keyword will be encountered, causing the loop to exit immediately.
Break ForEach-Object cmdlet Iteration
To break out of a ForEach-Object
loop in PowerShell, you can use the break
keyword. The break
keyword immediately exits the loop and continues execution of the script after the loop. Here is an example of using break
in a ForEach-Object
loop:
#Get All running processes
$Processes = Get-Process
$Counter = 1
#Iterate through each process
$Processes | ForEach-Object {
Write-host "Processing Item $Counter of $($Processes.count)"
if ($_.Name -eq "notepad") {
Write-Host "Found Notepad process and exiting from the Loop!"
break
}
$Counter++
}
Write-Host "Finished processing processes"
In this example, the script gets a list of processes using Get-Process
and iterates over each process using ForEach-Object
. If the name of the process is “notepad”, a message is displayed and the break
keyword is used to exit the loop. The script then continues execution after the loop.
Continue in PowerShell ForEach Loop
The continue
keyword to skip the current element in the loop and continues with the next iteration of the loop. For example:
#PowerShell ForEach 1..10
$Array = 1..10
Foreach($Val in $Array){
#Skip 5
if($val -eq 5){
Continue
}
Write-Host "Value: $val"
}
Output:
Value:Â 1
Value:Â 2
Value:Â 3
Value:Â 4
Value:Â 6
Value:Â 7
Value:Â 8
Value:Â 9
Value:Â 10
In the example above, the foreach
loop will iterate through the elements of the $array
array. When the loop reaches the element with a value of 5, the continue
keyword will be encountered, causing the loop to skip the remainder of the current iteration and move on to the next one.
Continue in ForEach-Object cmdlet
However, When you use break or continue in ForEach-Object cmdlet, the whole loop is terminated instead of skipping the current iteration. You have to use “Return” instead of “Continue”.
#Loop between 1 to 10 numbers
1..10 | ForEach-Object {
if ($_ -eq 5) {
return
}
Write-host $_
}
Output:
Value:Â 1
Value:Â 2
Value:Â 3
Value:Â 4
Value:Â 6
Value:Â 7
Value:Â 8
Value:Â 9
Value:Â 10
Conclusion
As you can see, the ForEach loop and ForEach-Object cmdlets are very useful for working with collections of objects that allow you to iterate and perform an action on each object. By using them in your PowerShell scripts, you can perform complex actions on large collections of objects efficiently.