fbpx Work with Each Item in a List or Windows PowerShell Command Output | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

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:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say