PowerShell: ForEach Loop Examples

PowerShell Foreach Loop

Looping is a foundational concept in PowerShell, integral to the very essence of programming. It becomes essential in various scenarios where we need to process one object at a time within an array or collection of objects.

According to Microsoft’s documentation on Foreach, it is described as a mechanism for “stepping through (iterating) a series of values in a collection of items” — a concise technical description that encapsulates its utility.

This post aims to demystify the ForEach Loop in PowerShell with practical examples.

Basic ForEach Statement

To grasp the fundamental concept, let’s consider a basic example where we iterate through an array of letters and display each letter in the terminal.

# PowerShell Foreach Loop Example
$letterArray = "a","b","c","d"
foreach ($letter in $letterArray)
{
  Write-Host $letter
}
PowerShell Foreach Example

This straightforward example follows the principles outlined in the Microsoft Docs, showcasing the simplicity and effectiveness of a ForEach loop.

ForEach with Get-ChildItem

Now, let’s dive into a more practical application. The following PowerShell script traverses the files within the directory that it runs from in the terminal, displaying details for all files in the folder.

# PowerShell Foreach Loop Example, get files within directory
foreach ($file in Get-ChildItem)
{
    Write-Host $file
    Write-Host $file.length
    Write-Host $file.lastaccesstime
}
PowerShell Foreach Loop Get Files in Directory

By leveraging the Get-ChildItem cmdlet, this example demonstrates how ForEach can be a powerful tool for iterating through file details. The output includes not just file names but also additional information like file length and last access time.

Understanding and mastering the ForEach loop in PowerShell opens up a world of possibilities for efficient data processing and automation. Whether dealing with arrays or collections of objects, ForEach proves to be an invaluable asset in your scripting arsenal.

Feel free to experiment and expand upon these examples, and let me know if you have any questions or if there are specific aspects of PowerShell you’d like to explore further. Happy scripting!


Leave a Reply

Your email address will not be published. Required fields are marked *

Popular Posts

Blog Categories