Menu & Search

PowerShell ForEach Loop Tutorial

PowerShell ForEach Loop Tutorial

Looping is a fundamental concept in PowerShell, and in programming in general. It’s needed for various situations where we need to work with one object at a time within an array/collection of objects.

Microsoft’s documentation on this, about Foreach : Microsoft Documentation, describes Foreach to be for ‘stepping through (iterating) a series of values in a collection of items‘ – always appreciate a good technical description.

This post contains some basic examples of the ForEach Loop in PowerShell:
# Basic ForEach Statement
# ForEach with Get-ChildItem

Basic ForEach Statement

We can hardcode anything into this array below, or populate it from somewhere else.

This is one of the most basic examples as shown in MS Docs, we’re iterating through each letter in the letterArray, writing to the terminal the value foreach loop.

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

ForEach with Get-ChildItem

The PowerShell script below performs a write-to Console for each file in the demoFolder Directory.

I’m running this twice, the second time navigating out of the demoFolder.

foreach ($file in Get-ChildItem)
{
    Write-Host $file
    Write-Host $file.length
    Write-Host $file.lastaccesstime
}
PowerShell ForEach Get-ChildItem

The above is also showing us the LastAccessTime Property for each file.

0 Comments