Home ยป PowerShell Foreach Loop

PowerShell Foreach Loop

The Foreach loop in PowerShell allows you to iterate through each item in a collections, such as array, collection of objects, or the output of a cmdlet.

It simplifies the process of iterating over data and performing on each item individually.

Syntax of the Foreach Loop

The syntax of the foreach loop in PowerShell is as follows.

foreach($item in $collection){
     
    # code to execute for each item
}

In this syntax:

  • $item: represents the current item being iterated over.
  • $collection: is the array or collection of items being iterated.

How to Iterate Over Arrays using Foreach Loop in PowerShell

$languages = @("Python","PowerShell","Rust","Java")

foreach($lang in $languages) {

     Write-Host "Language: $lang"

}

In the above PowerShell script, the $languages is an array that stores the languages. Using the foreach loop, it iterates over the collection of items in the array and print the language in the console.

Language: Python
Language: PowerShell
Language: Rust
Language: Java

How to Iterate over Outputs from Cmdlets using Foreach Loop in PowerShell

Get-Process | foreach {
   Write-Host "Process Name: $_.Name, ID: $_.Id"
}

In the above PowerShell script, the Get-Process cmdlet outputs the list of processes as a input to the foreach loop.

Cool Tip: How to use foreach-object in PowerShell!

Conclusion

I hope the above article on how to use the foreach loop in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.