Skip to content

Lesson 3 of 13 · 14m

Filter Left, Shape Right

Push predicates to the data source with -Filter parameters, then shape what arrived with Where-Object, Select-Object, and Group-Object.

Get-ADUser -Filter * on a directory with 200,000 users is a self-inflicted denial of service. Every object comes over the wire, gets hydrated, and crawls down your pipeline so Where-Object {$_.Enabled -eq $true} can throw most of it away. The domain controller did all the work; you did all the discarding. Get-ADUser -Filter 'Enabled -eq $true' sends the predicate to the DC as an LDAP filter and returns only what matches. Same result, two orders of magnitude less traffic.

Filter left

The rule is mechanical: push selection as close to the data source as the API allows. -Filter, -Query, -Name, -Path, -Id, -Include — parameters on the cmdlet — run where the data lives. Where-Object runs in your process, after everything already arrived.

The trap is that parameters don't compose like predicates. Get-ChildItem -Path C:\inetpub -Filter *.log is a directory-level filter passed to the filesystem. -Include *.log looks the same but only engages when -Recurse is set or the path ends in a wildcard — and it evaluates after enumeration in PS 5.1, so it's slower. Get-WinEvent -FilterHashtable @{LogName='System'; Level=2} queries the event log service directly; Get-EventLog then Where reads the world first.

Where-Object itself has two grammars. The scriptblock form, {$_.Status -eq 'Running' -and $_.StartType -eq 'Automatic'}, accepts any expression including method calls. The simplified form added in PowerShell 3.0, Where-Object Status -eq Running, is one property, one operator, one value — faster to write, marginally faster to run, and it cannot express -and, -or, -not, nested properties, or method calls. Reach for the scriptblock the moment the predicate gets interesting.

Shape right

After selection comes projection, and the operators do different jobs:

  • Sort-Object -Property CPU -Descending — accepts a comma list for multi-key sorts and -Unique to dedupe. -Stable (added in PowerShell 6.2) preserves input order on ties; without it equal keys come back in arbitrary order.
  • Select-Object — row picker (-First, -Last, -Skip, -SkipLast, -Unique) or column projector (Select Name, Id) or property unroller (-ExpandProperty Name). Three jobs wearing one name.
  • Group-Object -Property Status — returns GroupInfo objects with .Count and .Group, the answer to "how many services per state."
  • Measure-Object -Sum -Average -Maximum — aggregates over numeric properties.
  • ForEach-Object — the per-object escape hatch for side effects: Get-Process | ForEach-Object {$_.Kill()}.

ForEach-Object has three siblings people confuse it with. foreach ($s in Get-Service) is the language statement — loads the whole collection first, then iterates fast; use it when you need the collection twice. .ForEach({...}) is the PS4+ collection method — fastest, still materializes everything. ForEach-Object is the pipeline cmdlet — streams, one object at a time, lowest memory. In PowerShell 7 there's a fourth: ForEach-Object -Parallel, which runs the scriptblock across runspaces with -ThrottleLimit (default 5). Outer variables need the $using: prefix inside it — $using:Path — because each parallel runspace gets its own scope. Anything that writes shared state from -Parallel without synchronization is a race condition you shipped yourself.

The pipeline is lazy — until it isn't

Objects flow through Where, ForEach, and Select one at a time; memory stays flat. Sort-Object, Group-Object, and Measure-Object must drain the entire pipeline before emitting anything — they buffer everything you filtered. Sorting a million objects is a memory decision, not just a time decision.

Evidence and practice

Invoke-Command -ComputerName (Get-Content all-servers.txt) { Get-Service } | Where Status -eq Stopped pulls every service object from every server across WinRM. -Filter can't apply — Get-Service has no status filter — but the pipeline still streams, so this is fine. What's not fine is Get-WinEvent -LogName Security on a busy DC to find one 4624: that's Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624; StartTime=(Get-Date).AddHours(-1)} or a -FilterXPath, never a client-side Where.

The habit: read the cmdlet's parameter list before reaching for Where-Object. If the provider can exclude at the source — Get-ADUser -Filter, Get-WinEvent -FilterHashtable, Get-CimInstance -Filter, -Query — let it. Where-Object is for predicates the API can't express, applied to data that already arrived.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.