POWERSHELL / CHAPTER 03

Work with object pipelines

Beginner

Filter, project, and sort data before formatting it.

By the end of this chapter

  • Use the current pipeline object
  • Choose Where-Object and Select-Object deliberately
  • Place display formatting at the end

The idea

PowerShell pipelines normally pass objects rather than only text lines. Where-Object retains objects matching a condition, Select-Object chooses or constructs properties, and Sort-Object orders objects by property values. Inside a pipeline script block, $_ refers to the current object. Follow the changing object shape at each stage to understand which properties remain available.

Display formatting belongs at the end of a pipeline intended for people. Format-Table produces formatting instructions, not the original domain records, so passing its output to further data processing or CSV export loses the expected shape. Create a compact sample of objects and inspect their properties directly. A reusable function should usually emit useful objects and let its caller choose the final display or serialization.

PowerShell example
$rows = @([pscustomobject]@{Name="Ada";Score=5}, [pscustomobject]@{Name="Bo";Score=2})
$names = $rows | Where-Object { $_.Score -ge 4 } | Select-Object -ExpandProperty Name
$names
Result
Ada

The predicate retains only Ada’s record, then ExpandProperty emits the Name value itself rather than a one-property object.

Try it yourself

Filter records to active users, sort by score descending, and emit only Name and Score properties.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which command keeps only objects satisfying a predicate?