0
0
PowerShellscripting~5 mins

ForEach-Object for iteration in PowerShell

Choose your learning style9 modes available
Introduction

ForEach-Object helps you do something to each item in a list one by one. It makes repeating tasks easy.

You want to print each name from a list of names.
You need to change all file names in a folder.
You want to check each number in a list and do math on it.
You want to send an email to every person in a contact list.
Syntax
PowerShell
list | ForEach-Object { script_block }

The list is the collection of items you want to work on.

The script_block is the code inside curly braces { } that runs for each item.

Examples
This prints each fruit name as it is.
PowerShell
'apple','banana','cherry' | ForEach-Object { $_ }
This changes each fruit name to uppercase.
PowerShell
'apple','banana','cherry' | ForEach-Object { $_.ToUpper() }
This doubles each number in the list 1, 2, 3.
PowerShell
1..3 | ForEach-Object { $_ * 2 }
Sample Program

This script takes a list of fruits and prints a sentence for each one.

PowerShell
$fruits = 'apple','banana','cherry'
$fruits | ForEach-Object { "I like $_" }
OutputSuccess
Important Notes

$_ is a special variable that means the current item in the list.

You can use ForEach-Object in pipelines to process data step-by-step.

Summary

ForEach-Object runs code on each item in a list.

Use $_ inside the script block to refer to the current item.

It helps automate repetitive tasks easily.