foreach-object powershell command

ForEach-Object | Taking on PowerShell one cmdlet at a time | Weekly Blog

Share this post:

This is a part of an on-going blog series written by Adam Gordon. Each week, Adam will walk you through a PowerShell command, showing you when and how to use each one. This week, Adam covers ForEach-Object.

When to use ForEach-Object

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.

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

  • Script block. Within the script block, use the $_ variable to represent the current object. The script block is the value of the –Process parameter. The script block can contain any PowerShell script.
  • Operation statement. You can also write an operation statement, which is much more like natural language. You can use the operation statement to specify a property value or call a method.


How to use ForEach-Object

Divide integers in an array: 

32070, 546208, 121233452 | ForEach-Object -Process {$_/1024}

This command takes an array of three integers and divides each one of them by 1024.

ForEach-Object powershell command


Get the name of all the files in a directory:

Get-ChildItem $pshome | ForEach-Object -Process {if (!$_.PSIsContainer) {$_.Name; ” ” }}

This command gets the files and directories in the PowerShell installation directory $pshome and passes them to the ForEach-Object cmdlet.

If the object is not a directory, the script block gets the name of the file and adds a space (” “) to separate it from the next entry.

The cmdlet uses the PSISContainer property to determine whether an object is a directory.

ForEach-Object powershell command


Operate on the most recent System events:

$Events = Get-EventLog -LogName System -Newest 3000

$Events | ForEach-Object -Begin {Get-Date} -Process {Out-File -FilePath C:\PShellTest\Events.txt -Append -InputObject $_.Message} -End {Get-Date}

This command gets the 3000 most recent events from the System event log and stores them in the $Events variable. It then pipes the events to the ForEach-Object cmdlet.

The –Begin parameter displays the current date and time.

Next, the -Process parameter uses the Out-File cmdlet to create a text file that is named Events.txt and stores the message property of each of the events in that file.

Last, the -End parameter is used to display the date and time after all of the processing has completed.

ForEach-Object powershell command

Learn last week’s command: Where-Object.

Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.

Leave a Reply

Your email address will not be published. Required fields are marked *