PowerShell Cmdlet Deep Dive: ForEach-Object
Welcome back to Wahmans PowerShell Blog! Today, we’re exploring one of the most commonly used cmdlets in PowerShell: ForEach-Object. According to Microsoft, this cmdlet “Performs an operation against each item in a collection of input objects.” Whether you’re piping data out of a command or looping through large lists, ForEach-Object enables powerful inline processing of objects in the pipeline.
What is ForEach-Object?
ForEach-Object is used primarily in the pipeline to perform operations on each item that passes through it. It’s different from the foreach keyword (used in script blocks outside of the pipeline) and is optimized for streaming data one item at a time.
Basic Syntax
INPUT | ForEach-Object { SCRIPTBLOCK }
Example 1: Basic Number Output (Beginner)
Let’s start with a simple example: printing squares of numbers 1 through 5.
1..5 | ForEach-Object { $_ * $_ }
Output: 1 4 9 16 25
$_ represents the current object in the pipeline.
Example 2: Working With Files (Intermediate)
List all .txt files in a directory and print their full paths:
Get-ChildItem -Path "C:\Temp" -Filter "*.txt" | ForEach-Object { $_.FullName }
This is great when you need to iterate over file objects and access their properties.
Example 3: Modifying Each Object (Intermediate)
Use ForEach-Object to update multiple services’ startup types to Manual:
"Spooler", "W32Time" | ForEach-Object {
Set-Service -Name $_ -StartupType Manual
}
This is an example of how ForEach-Object helps apply changes to each item in a list.
Example 4: Advanced Use with Begin, Process, End Blocks
ForEach-Object also supports script block segments: -Begin, -Process, and -End.
1..5 | ForEach-Object -Begin { $sum = 0 } -Process { $sum += $_ } -End { "Total sum: $sum" }
This example calculates a running total of numbers and outputs the result at the end.
Wrap Up
Whether you’re parsing files, automating service configs, or crunching data, ForEach-Object is indispensable for stream processing in PowerShell. Its support for script blocks at different stages of the pipeline adds even more flexibility.
Happy scripting, and I will see you in the next post!
Leave a Reply