O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Processing Collections Using ForEach-Object

PowerShell provides language features for iterating over collections using the for operator. However, its imperative nature often makes iteration clumsy and error prone, as we usually have to repeat the same loop code over and over again. The ForEach-Object cmdlet minimizes the repetition by applying an action to each object, collecting the results into a new collection.

At a bare minimum, ForEach-Object requires two inputs: a collection, usually piped in from the previous command, and an action. Actions are expressed as script blocks. To paraphrase the old proverb, an example is worth a thousand words, so here is how we can get the file sizes for all files in the current folder by passing a script ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required