Home » PowerShell ForEach-Object

PowerShell ForEach-Object

by Online Tutorials Library

PowerShell ForEach-Object

The ForEach-Object in PowerShell executes a block of statements against each item in a collection of input objects. These objects are passed through the pipeline or specified by using the -InputObject parameter.

With the Starting of PowerShell version 3.0, following are the two different ways for constructing the ForEach-Object command:

  1. Operation Statement
  2. Script Block

Syntax

Parameters

Following are the different parameters used in the ForEach-Object cmdlet:

-MemberName

This parameter is used to specify the method for calling and the property to get.

-ArgumentList

This parameter is used to specify the array of arguments for calling a method.

-Confirm

This parameter prompts you a confirmation before executing the cmdlet.

-InputObject

This parameter is used to specify the input objects. The cmdlet executes the block of script or the operation statement on each input object. When we use this parameter in the ForEach-Object, the value of this parameter is treated as a single object.

-WhatIf

This parameter is used to display what would happen if the cmdlet executes. The cmdlet will not execute.

-Process

This parameter is used to specify the operation, which is performed on each input object. Enter the script block, which describes the operation.

-Begin

This parameter is used to specify the script block, which executes before the cmdlet processes any input object.

-End

This parameter is used to specify the script block, which executes after the cmdlet processes all the input objects.

-RemainingScripts

This parameter is used to specify all those script blocks, which are not taken by the -Process parameter.

Example: Access the files and folders from the D: drive

PowerShell ForEach-Object

In this example, we use the pipe (|) sign, which is used to pass the output of get-childitem to the ForEach-Object command. And the write-host is used to display that values.

In the command, $_ is a special variable that processes any value which is passed through the pipe.


You may also like