The Pipeline
Hand whole objects from one command to the next, and filter, sort, count and group them on the way.
Updated
Passing Objects
- The Pipeline: | (Apprentice): The pipe, |, hands every object one command makes to the next command whole, with all its properties, so you can build a job out of small steps and read it from left to right.
Filter, Sort, Count
- Filtering: Where-Object and Comparisons (Apprentice): Where-Object keeps only the objects that pass a test, such as every file over 1 MB or every song, and the test is written with comparisons read aloud as words, -eq "equals", -gt "greater than", -like "is like", with $_ standing for this item.
- Sorting: Sort-Object (Apprentice): Sort-Object puts objects in order by any property, smallest or A first unless you add -Descending, and with Select-Object -First after it gives you the top ten of anything, such as the ten biggest files on a drive; -Unique lists each value once.
- Counting and Grouping: Measure-Object and Group-Object (Apprentice): Measure-Object counts the objects a pipeline hands it and adds up, averages or finds the largest of one property, such as the total size of every file, and Group-Object sorts objects into piles by a property, such as one pile per file type, each with a count.
Acting on Each
- Doing Something to Each: ForEach-Object (Apprentice): ForEach-Object runs a script block once for every object the pipeline hands it, with $_ as this item, so one line can rename 200 photos, and -WhatIf goes inside the braces, on the command that makes the change, so you can rehearse first.
- Columns You Make Yourself: Calculated Properties (Journeyman): A calculated property is a column you add to Select-Object yourself, written as a hashtable with a Name for the heading and an Expression that works the value out for each object, such as a file's size in megabytes, rounded with [math]::Round.
Exercise: The Ten Biggest Files
- Exercise: The Ten Biggest Files (Apprentice): Find out what's filling a full laptop's 24 made-up files with the pipeline (a count, the ten biggest, the big videos, the files of each type and a table of sizes in KB, each saved as a report) and rename its screenshots with ForEach-Object, while a Pester check tells you which answers are right.