Perform an operation (execute a block of statements) against each of a set of input objects. '%' is an alias for the ForEach-Object.
Syntax
ForEach-Object [-process] ScriptBlock[] [-inputObject psobject]
[-begin scriptblock] [-end scriptblock] [CommonParameters]
key
-process ScriptBlock[]
A block of powershell script that is applied to each incoming object.
-inputObject psobject
Accepts an object that the script block specified in the process parame
ter will act upon. Enter a variable that contains the objects or type a
command or expression that gets the objects.
-begin scriptblock
A script block to run before processing any input objects.
-end scriptblock
A script block to run after processing all input objects.
CommonParameters:
-Verbose, -Debug,-ErrorAction,-ErrorVariable, -OutVariable.
ForEach-Object has an alias: ForEach but, rather confusingly there is also a built-in ForEach statement which will often take precedence.
Use the ForEach statement when the collection of objects is small enough that it can be loaded into memory.
Use the ForEach-Object cmdlet when you want to pass only one object at a time through the pipeline, minimising memory usage.
Examples
Retrieve the files (and folders) from the C: drive and display the size of each:
PS C:>get-childitem C:\ | foreach-object -process { $_.length / 1024 }
(The $_ variable holds a reference to the current item being processed.)
Retrieve the 1000 most recent events from the system event log and store them in the $my_events variable:
PS C:>$my_events = get-eventlog -logname system -newest 1000
Then pipe the $my_events variable into the ForEach-Object cmdlet.
PS C:>$my_events | foreach-object -begin {get-date} `
-process {out-file -filepath event_log.txt -append -inputobject $_.message} `
-end {get-date}
In this example, the -Process parameter uses Out-File to create a text file and stores the .message property of each event. The -Begin and -End parameters are used to display the date and time before and after the command has completed.
"The best way to have a good idea is to have a lot of ideas" - Linus Pauling
Related Powershell Commands:
compare-object Compare the properties of objects
group-object - Group the objects that contain the same value for a common property
measure-object - Measure aspects of object properties and create objects from those values
new-object - Create a new .Net object
select-object - Select objects based on parameters set in the Cmdlet command string
sort-object - Sort the input objects by property value
tee-object - Send input objects to two places
where-object - Filter input from the pipeline allowing operation on only certain objects