Contact Info

Crumbtrail

ActiveXperts.com » Administration » Powershell » Powershell 3.0 » ForEach-Object

ForEach-Object - Powershell 3.0 CmdLet

ActiveXperts Network Monitor ships with integrated Powershell scripts to monitor complex network. The scripts run out of the box
Download the ActiveXperts Network Monitor FREE version now »

ForEach-Object

Short description
Performs an operation against each item in a collection of input objects.

Syntax
ForEach-Object [-Process] <ScriptBlock[]> [-Begin <ScriptBlock>] [-End <ScriptBlock>] [-InputObject <PSObject>] [-Remai
ningScripts <ScriptBlock[]>] [-Confirm] [-WhatIf] [<CommonParameters>]
ForEach-Object [-MemberName] <String> [-ArgumentList <Object[]>] [-InputObject <PSObject>] [-Confirm] [-WhatIf] [<Commo
nParameters>]





Description
The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. The input objects can be
 piped to the cmdlet or specified by using the InputObject parameter.


Beginning in Windows PowerShell 3.0, there are two different ways to construct a  ForEach-Object command.


Script block. You can use a script block to specify the operation. Within the script block, use the $_ variable to repr
esent the current object. The script block is the value of the Process parameter. The script block can contain any Wind
ows PowerShell script.


For example, the following command gets the value of the ProcessName property of each process on the computer.


Get-Process | ForEach-Object {$_.ProcessName}


Operation statement. You can also write a operation statement, which is much more like natural language. You can use th
e operation statement to specify a property value or call a method. Operation statements were introduced in Windows Pow
erShell 3.0.


For example, the following command also gets the value of the ProcessName property of each process on the computer.


Get-Process | ForEach-Object ProcessName


When using the script block format, in addition to using the script block that describes the operations that are perfor
med on each input object, you can provide two additional script blocks. The Begin script block, which is the value of t
he Begin parameter, runs before the first input object is processed. The End scrip block, which is the value of the End
 parameter, runs after the last input object is processed.