Powershell

How to Use ForEach-Object in PowerShell

The “ForEach-Object” cmdlet is utilized for performing operations on each object item that is available in the input collection of objects. Moreover, it is a valuable cmdlet when users are required to work with a group of objects. These input objects can be piped to a particular command with the aid of the “-InputObject” parameter. It iterates over the set of objects, passes to the pipeline, and then takes action.

This blog will discuss the “ForEach-Object” cmdlet in comprehensive detail.

How to Use ForEach-Object in PowerShell?

As described in the above section the stated cmdlet is used to perform an operation on every object present in the specific group of objects. Let’s have a look at the practical demonstration of the stated command.

Example 1: Divide the Integers in an Array with the Aid of “ForEach-Object” Cmdlet

Execute the below-given command to divide the provided list of integers in an array:

99943, 72834, 89323 | ForEach-Object -Process {$_/512}

 
In accordance with the above code:

    • First, specify the integers list along with the “|” pipeline.
    • After that, add the “ForEach-Object” cmdlet.
    • Lastly, write the “-Process” parameter and provide the stated filter:


Example 2: Retrieve the Length of All the Files or Folders Available in the Specific Directory

To get the length of all the files and folders, run the following command:

Get-ChildItem $PSHOME | ForEach-Object -Process {if (!$_.PSIsContainer) {$_.Name; $_.Length / 512; " " }}

 
In the above-stated command:

    • First, write the “Get-ChildItem” cmdlet and the “$PSHOME” cmdlet along with the “|” pipeline.
    • Then, mention the “ForEach-Object” cmdlet.
    • Lastly, specify the “-Process” parameter and provide it with the stated condition:


Example 3: Use the “ForEach-Object” Cmdlet Along with Two Scripts

Run the below-mentioned code to use the “ForEach-Object” cmdlet along with the two scripts:

1..2 | ForEach-Object {'first'} {'last'}

 
According to the above-given command:

    • First, write the provided condition along with the “|” pipeline.
    • After that, use the “ForEach-Object” cmdlet and specify the two scripts:


That’s all! We have explained the usage of the “ForEach-Object” command in PowerShell.

Conclusion

The “ForEach-Object” cmdlet is responsible for iterating over the objects and performing operations on each object in the collection of input objects. This write-up has covered all the possible aspects of the cmdlet “ForEach-Object” in detail with the aid of several examples.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.