Work with Each Item in a List or Command Output

1. Problem

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

2. Solution

Use the Foreach-Object 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 | Foreach-Object { $_ * 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:

        Get-ChildItem *.txt | Foreach-Object { 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 = Get-Process notepad
        $notepadProcesses | Foreach-Object { $_.WaitForExit() }


3. Discussion

Like the Where-Object cmdlet, the Foreach-Object cmdlet runs the script block that you specify for each item in the input. A script 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. For more information about script blocks, see Section 10.3, “Write a Script Block.” For more information about the type of comparisons available to you, see “Comparison Operators” in Appendix A.

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

        1..10

This is PowerShell’s array range syntax, which you can learn more about in Section 11.3, “Access Elements of an Array.”

The Foreach-Object 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 information on how to use those keywords, see Section 4.4, “Repeat Operations with Loops.”

For more information about the Foreach-Object cmdlet, type Get-Help Foreach-Object.

For more information about dealing with pipeline input in your own scripts, functions, and script blocks, see Section 10.7, “Access Pipeline Input.”

Tags: , , , , , , ,