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 , describes it as ‘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, including the following:
> Basic PowerShell For Each Example
> ForEach with Get-ChildItem
Basic PowerShell For Each Example
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 with Get-ChildItem Example
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 }
The above is also showing us the LastAccessTime Property for each file.
Hope this was useful!
Leave a Reply