Skip to main content

Work with Each Item in a List or Windows PowerShell Command Output

Problem

You have a list of items and want to work with each item in that list.

Solution

Use the ForeachObject cmdlet (which has the standard aliases foreach and %)to work with each item in a list.

To apply a calculation to each item in a list, use the $_ variable as part of a calculation in the scriptblock parameter:

PS >1..10 | ForeachObject { $_ * 2 } 2 4 6 8 10 12 14 16 18 20

To run a program on each file in a directory, use the $_ variable as a parameter to the program in the script block parameter:

GetChildItem *.txt | ForeachObject { attrib –r $_ }

To access a method or property for each object in a list, access that method or property on the $_ variable in the script block parameter. In this example, you get the list of running processes called notepad, and then wait for each of them to exit:

$notepadProcesses = GetProcess notepad $notepadProcesses | ForeachObject { $_.WaitForExit() }

Discussion

Like the WhereObject cmdlet, the ForeachObject cmdlet runs the script block that you specify for each item in the input. Ascript block is a series of PowerShell commands enclosed by the { and } characters. For each item in the set of incoming objects, PowerShell assigns that item to the $_ variable, one element at a time. In the examples given by the solution, the $_ variable represents each file or process that the previous cmdlet generated.

This script block can contain a great deal of functionality, if desired. You can combine multiple tests, comparisons, and much more.

The first example in the solution demonstrates a neat way to generate ranges of numbers:

1..10

This is PowerShell’s array range syntax.

The ForeachObject cmdlet isn’t the only way to perform actions on items in a list. The PowerShell scripting language supports several other keywords, such as for,(a different) foreach, do, and while.

For more information about the ForeachObject cmdlet, type GetHelp ForeachObject.

Help Category