Imagine a baker with a tray of 24 cookies. Instead of writing 24 separate notes saying "put icing on cookie 1, put icing on cookie 2," the baker simply says: "For each cookie on this tray, add a dab of icing."
In Windows PowerShell, ForEach-Object lets you do the exact same thing with files, folders, or text lists. You write an action once, and PowerShell repeats it automatically for every item in your list.
Meet the Special Placeholder: $_
When items travel through a PowerShell pipeline (|) into ForEach-Object, PowerShell hands them to your command one at a time. Inside the curly braces { ... }, the special symbol $_ (or $PSItem) stands for "the current item I am holding right now."
# Greet three people using one short loop
"Adi", "Budi", "Citra" | ForEach-Object {
Write-Output "Hello, $_! Welcome to PowerShell."
}
Practical Example: Checking File Sizes Safely
Suppose you want to see the name and size of every .txt file in your current folder. You can list them with Get-ChildItem and pass each one into ForEach-Object:
# List each .txt file and print its name and size in bytes
Get-ChildItem -Filter "*.txt" | ForEach-Object {
Write-Output "$($_.Name) is $($_.Length) bytes"
}
Notice how $_.Name grabs the file's name and $_.Length grabs its sizeājust like reading labels off each item on a conveyor belt.
3 Things to Remember
- Write once, repeat many times: Pipe any list into
ForEach-Object { ... }to run the same step on every item. $_means "this current item": Use$_.Nameor$_.Lengthto read properties of the item currently being processed.- Test with
Write-Outputfirst: Before renaming or moving files in a loop, print what would happen so you can verify safely.