Objects in the pipeline

PowerShell · Essentials · 10 min

Thinking in objects instead of text columns is what makes PowerShell different from bash.

In bash, commands exchange text and you parse it with cut, awk and regexes. In PowerShell, cmdlets output .NET objects, and the pipeline | passes those objects to the next command intact. Get-Process emits Process objects, Get-ChildItem emits FileInfo and DirectoryInfo objects, and so on. What you see on screen is only a formatted view chosen at the very end.

Because they are objects, you can:

  • read properties directly: (Get-Date).Year, $file.Length,
  • call methods: "text".ToUpper(), (Get-Date).AddDays(7),
  • sort, filter and select by property name without any parsing.

Get-Member (alias gm) is how you find out what an object offers: pipe anything into it to see its type name, properties and methods. Expect more properties than the default table shows; Select-Object * reveals them all.

Parentheses run a command first and let you use its result as a value: (Get-ChildItem).Count. When you access a property on a collection, PowerShell applies it to each element (member enumeration), so (Get-Process).Name returns every process name.

Native programs such as git or ping still output text: each line becomes a string object in the pipeline.

Example

$p = Get-Process -Id $PID                # the current PowerShell process
$p.GetType().FullName                    # System.Diagnostics.Process
$p.ProcessName                           # pwsh
$p | Get-Member -MemberType Method | Select-Object -First 2 Name
Get-ChildItem $PSHOME -File |
  Sort-Object Length -Descending |
  Select-Object -First 3 Name, Length    # properties, not text columns
(Get-Date).AddDays(7).DayOfWeek          # e.g. Saturday
'hello'.ToUpper()                        # HELLO
(1..5 | Measure-Object -Sum).Sum         # 15
(Get-ChildItem $PSHOME -File).Count      # member enumeration on a collection

Remember

  • The pipeline passes objects, not text
  • Pipe to Get-Member to see properties and methods
  • (command).Property uses the result as a value

Watch out for

  • Parsing the formatted table output with string methods instead of using the object's properties.

Check yourself

  1. What travels between `Get-ChildItem | Sort-Object Length`?
  2. Which command shows the properties and methods of an object?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines